laravel5.1のマイグレーションでエラー
Laravelのマイグレーションを実行するときに、
1215 Cannot add foreign key constraint
とエラーが出て結構悩みましたけど解決したので、メモしておきます。
ちなみにLaravel5.1(LTS)です。
未だに理解しかねる部分があるのですが、
今回エラーがでた時のマイグレーションファイルは
デフォルトのusersテーブルと
<?php public function up() { Schema::create('entries', function(Blueprint $table){ $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('title', 85)->unique(); $table->text('body'); $table->timestamps(); $table ->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade')->onUpdate('cascade'); }); }
というentriesテーブルのマイグレーションファイルの時にエラーができました。
今回はこれに、
<?php $table->engine = 'InnoDB';
を追加するとエラーがなくなりました。
General error: 1215 Cannot add foreign key constraint
ここら辺の議論を参考にしました。
MyISAM doesn't support foreign keys and sometimes it's the default.
だそうです。
ただ、usersテーブルと以下のようなpostsテーブルの時はうまく行ったので
いまいちしっくりきません。
<?php public function up() { Schema::create('posts', function(Blueprint $table){ $table->increments('id'); $table->integer('user_id')->unsigned(); $table->text('content'); $table->timestamps(); $table ->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade')->onUpdate('cascade'); }); }
この場合はデフォルトで、InnoDBに設定されていたのでしょうか。
わけがわかりません。
とりあえず
外部キー設定する際には、
あえて
<?php $table->engine = 'InnoDB';
これを書いておいた方がよさそうです。
以上です。