Migrationファイルを使って、リレーション設定を行う際のちょっとした注意メモ。
エラーがでたファイル
<?php
//-- 略
class CreatePostsTable extends Migration
{
//-- 略
public function up()
{
Schema::create('Posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->bigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
}
//-- 略
上記のようなマイグレーションファイルをコマンドでmigrateしたときエラーが発生。
どうやら$table->foreign('user_id')->references('id')->on('users');
のようにuser_id
を外部キーとして使用している場合は、カラム定義の際に$table->bigInteger('user_id');
という記述を$table->bigInteger('user_id')->unsigned();
という感じでunsigned
をつなげて書く必要があるようです。(MySQLの場合)
OKだったファイル
<?php
//-- 略
class CreatePostsTable extends Migration
{
//-- 略
public function up()
{
Schema::create('Posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->bigInteger('user_id')->unsigned(); // 変更
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
}
//-- 略
ちょっとしたメモでした。