【发布时间】:2013-09-10 11:04:24
【问题描述】:
在 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 的迁移只会在之后运行mytable 的迁移已完成)。
我该如何解决这个问题?
【问题讨论】:
标签: mysql foreign-keys laravel laravel-4