Laravel迁移中的外键约束 [英] Foreign Key Constraint in Laravel Migration

查看:587
本文介绍了Laravel迁移中的外键约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 4中,如何在迁移中添加外键约束?



在迁移 mytable (它引用 foreigntable ):

  // add Column 
$ table
- > string('foreigntable_id',6);
$ b $ //添加FK
$表
- > foreign('foreigntable_id')
- >引用('id')
- > ; on('foreigntable');

错误:

  [例外] 
SQLSTATE [HY000]:一般错误:1005无法建立表'mydb。#sql-1a24_2
1a'(errno:150)(SQL:alter table` mytable`添加约束
mytable_foreigntable_id_foreign外键(`foreigntable_id`)引用
`foreigntable`(`id`))(Bindings:array(
))

我假设问题是当MySQL尝试添加外键时, foreigntable 不存在( mytable )的密钥约束(因为创建 foreigntable 的迁移只会在 之后运行迁移完成 mytable )。



如何解决这个问题?其实,我自己找到了答案。
$ b

mytable 的迁移移到新的迁移中: ($'$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' ('id')
- > on('foreigntable');

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


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?

解决方案

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.

这篇关于Laravel迁移中的外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆