【问题标题】:Foreign Key Constraint in Laravel MigrationLaravel 迁移中的外键约束
【发布时间】: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


    【解决方案1】:

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

    mytable 的迁移中的以下内容移到新的迁移中:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-20
      • 2019-12-24
      • 2019-03-24
      • 2017-03-27
      • 2018-04-01
      • 1970-01-01
      • 2020-03-12
      相关资源
      最近更新 更多