Laravel5.5のmigrationで、外部キー制約を貼ろうとして躓いた話
概要
業務でLaravel5.5を使っているので、家で学習がてらLaravelを触っていました。
そこで、外部キー制約を貼ったテーブルを作成しようとして躓いたので、忘れないように残しておきます。
やろうとしたこと
ブログ投稿を管理するpostsテーブルと、そのブログに投稿するコメントを管理するcommentsテーブルを作成しようとしました。
※CakePHPのブログチュートリアルから持ってきました。
postsテーブルを作成するmigrationファイル
public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); }); }
commentsテーブルを作成するmigrationファイル
public function up() { Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->string('commenter'); $table->text('body'); $table->integer('posts_id'); $table->foreign('posts_id')->references('id')->on('posts'); $table->timestamps(); }); }
結論
$table->integer('posts_id');
が原因でした。
この状態では、Laravelはint(11)
で生成するようです。
しかし、postsテーブルの$table->increments('id');
はint(10) unsigned
で生成するため、親テーブルと型が違う状態になり、エラーになっていました。
解決策としては、 $table->integer('posts_id')->unsigned();
としてやると、同じint(10) unsigned
で生成してくれ、無事migrationできました。
public function up() { Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->string('commenter'); $table->text('body'); $table->integer('posts_id')->unsigned(); $table->foreign('posts_id')->references('id')->on('posts'); $table->timestamps(); }); }
エラー文言が出て、それで検索をかけて四苦八苦していましたが、テーブル構造を見たら一発で解決できました。
その視点は忘れないように、ここに残します。