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?