資料遷移無法新增外來鍵約束,錯誤程式碼 1215

zoang發表於2018-06-29

錯誤問題排除項:
1、兩個欄位型別必須一致
2、資料庫引擎InnoDB
3、原有資料表欄位必須已加索引(重要)

例錯誤程式碼:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `user_addresses` add constraint `user_addr
  esses_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

解析:
原users表預設id已是主鍵,預設情況是不會出現上面錯誤的,但是像我愛折騰,users表用uid表示使用者識別碼,未設定索引,導致遷移表時報錯1215。
解決辦法:
新建users表uid欄位時加上索引index()

$table->bigInteger('uid')->index()->after('id');
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章