在 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 (
))
我假设问题是foreigntable
当 MySQL 尝试添加外键约束时不存在mytable
(因为创建的迁移foreigntable
只会在迁移完成后mytable
运行)。
我怎样才能解决这个问题?