Laravel迁移自引用外键问题 [英] Laravel migration self referencing foreign key issue

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

问题描述

您好我有一个使用迁移模式构建器创建表的问题。
问题出现在具有自引用外键的表中。
这里是产生错误的代码:
$ b $ pre $ $ $ c $ Schema :: create('cb_category',function($ table)

$ table-> integer('id') - > primary() - > unique() - > unsigned();
$ table-> integer ('cb_domain');
$('id') - > ('cb_category') - >整数('parent_id') - > nullable();
$表 - >外('parent_id') - >引用('id') - & - > onUpdate('cascade') - > onDelete('cascade');
$ table-> string('name');
$ table-> integer('level') ;
});

这是错误:

<$ p $ (SQL):[/ b] [/ b] [/ b] [/ b] $ c>

gory 添加约束cb_category_parent_id_foreign外键( parent_id )引用 cb_category id`)del
ete cascade on update cascade)(Bindings:array(
) p>

[PDOException]
SQLSTATE [HY000]:一般错误:1005无法创建表'eklik2。#sql-7d4_e'(errno:150)



有什么想法?

解决方案

一个创建列,另一个添加FK。 mysql不能同时做两个。


Hi I have a problem to create a table using migration schema builder. The problem occure with table with self referencing foreign key. Here is the code which produce error:

        Schema::create('cb_category', function($table)
    {
        $table->integer('id')->primary()->unique()->unsigned();
        $table->integer('domain_id')->unsigned();
        $table->foreign('domain_id')->references('id')->on('cb_domain'); 
        $table->integer('parent_id')->nullable(); 
        $table->foreign('parent_id')->references('id')->on('cb_category')->onUpdate('cascade')->onDelete('cascade'); 
        $table->string('name');
        $table->integer('level');
    });

Here is the error:

  SQLSTATE[HY000]: General error: 1005 Can't create table 'eklik2.#sql-7d4_e' (errno: 150) (SQL: alter table `cb_cate

goryadd constraint cb_category_parent_id_foreign foreign key (parent_id) referencescb_category(id`) on del ete cascade on update cascade) (Bindings: array ( ))

[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create table 'eklik2.#sql-7d4_e' (errno: 150)

Any idea?

解决方案

You have to break this into two Schema blocks, one creating the columns, the other adding the FKs. mysql can't do both at the same time.

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

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