0

在 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运行)。

我怎样才能解决这个问题?

4

1 回答 1

0

其实,我自己也找到了答案。

将以下内容从迁移迁移mytable到新迁移:

// add FK
$table
    ->foreign( 'foreigntable_id' )
    ->references( 'id' )
    ->on( 'foreigntable' );

由于新的迁移将在 迁移 之后以及 迁移之后运行mytableforeigntable因此两个表都将在添加外键约束时出现。因此它有效。

于 2013-09-06T11:34:45.643 回答