ラベル foreign key の投稿を表示しています。 すべての投稿を表示
ラベル foreign key の投稿を表示しています。 すべての投稿を表示

2017年5月26日金曜日

laravel foreign key migration error

下記foreign keyを指定しようと、エラーとなった。

$table->foreign('dept_id')->references('id')->on('depts');

[Illuminate\Database\QueryException]                                  
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`c9`.`#sql-acb_114`, CONSTRAINT `employees_dept_id_foreign` FOREIGN KEY (`dept_id`) REFERENCES `depts` (
  `id`)) (SQL: alter table `employees` add constraint `employees_dept_id_foreign` foreign key (`dept_id`) references `depts` (`id`))

原因は、外部Keyを追加したいtableはすでに値が入っている場合、nullableと指定しないといけない
$table-> unsignedInteger ('dept_id')->after('gender')->nullable();

参考:https://laracasts.com/discuss/channels/laravel/foreign-key-error-on-migration