问题
In Laravel 4, how can I add a foreign key constraint in a migration?
In the migration for mytable
(which references foreigntable
):
// add Column
$table
->string( 'foreigntable_id', 6 );
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
Error:
[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 (
))
I assume the problem is that foreigntable
does not exist when MySQL tries to add the foreign key constraint to mytable
(because the migration that creates foreigntable
will only be run after the migration for mytable
was finished).
How can I get around this problem?
回答1:
Actually, I just found the answer myself.
Move the following from the migration for mytable
into a new migration:
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
Since the new migration will be run after the migration for mytable
, as well as after the migration for foreigntable
, both tables will be present at the time that the foreign key constraints is added. Hence it works.
来源:https://stackoverflow.com/questions/18656207/foreign-key-constraint-in-laravel-migration