【Laravel】マイグレーションに関する自分用メモ

Laradockのロゴ画像
  • URLをコピーしました!

マイグレーションファイルやマイグレーションの実行に関して、忘れがちなことを自分用にメモ。

 

また何かあれば随時追加する予定です。

 

 

 

 

目次

textカラムの場合は、default修飾子が使えない

 

レコード作成時にデフォルト値として文字列を入れたい場合は、text型じゃなくてstring型にする必要がある。

 

public function up()
{
    Schema::create('example1', function (Blueprint $table) {
        $table->increments('id');
        //$table->text('hoge')->default('これだとマイグレーションした時にエラーが出るよ。');
        $table->string('fuga')->default('デフォルトのテキストを入れたいならstring型にすべし。');
    });
}

 

 

 

unsigned型にしてから外部キー制約をつける

 

外部キー制約を付けたい場合は、unsignedにする必要がある。

 

じゃないと、参照する主キーがunsigned型のため、「外部キーと参照した主キーの型が不一致です」みたいなエラーが出る。

 

public function up()
{
    Schema::create('example2', function (Blueprint $table) {
        $table->increments('id');                // incrementsにすると、自動でunsigned型になる
        $table->unsignedInteger('example1_id');  // なので、こっちもunsigned型にしなきゃダメ
        $table->foreign('example1_id')->references('id')->on('example1');
        //$table->integer('example1_id')->unsigned();  // こーゆー書き方もできる
        //$table->foreign('example1_id')->references('id')->on('example1');
    });
}

 

 

Integerの長さを指定したい時は、->length()で指定する

 

詳細はこちらの記事に書きました。

 

 

マイグレーションファイルのup()メソッドの例

 

...省略...
 
public function up()
{
    Schema::create('items', function (Blueprint $table) {
        $table->increments('id');  // 符号なしINTを使用した自動増分ID(主キー)
        $table->unsignedBigInteger('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('mail', 50);
        $table->string('status', 3)->default('出品中');
        $table->string('img', 50)->nullable();
        $table->string('name', 50);
        $table->text('description', 1000);
        $table->dateTime('exhibition_date_time');
        $table->unsignedInteger('price')->length(7); 
        $table->unsignedSmallInteger('fav')->length(3)->default(0);
        $table->timestamps();
    });
}
 
...省略...

 

 

 

 

参考URL

 

 

この記事を書いた人

コメント

コメントする

目次