在 Laravel 4 中,如何在迁移中添加外键约束?
在mytable
(引用foreigntable
)的迁移中:
// add Column
$table
->string( 'foreigntable_id', 6 );
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
错误:
[Exception]
SQLSTATE[HY000]: General error: 1005 Can't create table 'mydb.#sql-1a24_2
1a' (errno: 150) (SQL: alter table `mytable` add constraint
mytable_foreigntable_id_foreign foreign key (`foreigntable_id`) references
`foreigntable` (`id`)) (Bindings: array (
))
我假设问题是当MySQL尝试将外键约束添加到mytable
时foreigntable
不存在(因为创建foreigntable
的迁移code> 仅在 mytable
迁移完成后运行)。
如何解决这个问题?
最佳答案
事实上,我自己刚刚找到了答案。
将以下内容从 mytable
的迁移移至新迁移中:
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
由于新的迁移将在 mytable
迁移之后以及 foreigntable
迁移之后运行,因此两个表都将在外部表迁移时出现。添加了关键约束。因此它有效。
关于mysql - Laravel 迁移中的外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18656207/