Foreign Key Constraint in Laravel Migration

回眸只為那壹抹淺笑 提交于 2019-12-11 20:11:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!