2013-08-25 63 views
8

您好我有一个使用迁移架构生成器创建表的问题。 问题出现在具有自引用外键的表中。 这里是其产生错误的代码:Laravel迁移自引用外键问题

 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'); 
    }); 

以下是错误:

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

血污add constraint cb_category_parent_id_foreign foreign key (上德尔 ETE级联PARENT_ID ) references cb_category ( id`)上更新级联)(绑定:阵列( ))

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

任何想法?

回答

5

您必须将其分解为两个模式块,一个创建列,另一个添加FK。 mysql不能同时执行这两个操作。

+0

我打破它在2个语句,无论如何错误依然存在: Schema :: create(...); ('cb_category') - > onUpdate('cascade)'('cb_category') - >参考('id') - >外部('parent_id') - ') - > onDelete('cascade'); }); – gandra404

+1

解决打破。这里是代码: Schema :: create('cb_category',function($ table){...}); $ dbh = DB :: getPdo(); $ dbh-> query(“ALTER TABLE cb_category ADD CONSTRAINT fk_cb_category_parent_id FOREIGN KEY(parent_id)REFERENCES cb_category(id)ON DELETE NO ACTION ON UPDATE NO ACTION”); – gandra404

2

我可能就太晚了党,但官方文档声称,外键,以整数的情况下,必须->unsigned();

http://laravel.com/docs/4.2/schema#foreign-keys

Note: When creating a foreign key that references an incrementing integer, remember to always make the foreign key column unsigned.

此外,工匠不失败,如果你(因为我)拼写错误unsigned(),我花了好几个小时试图找出为什么没有创建密钥。

所以两件事情:1。 始终使外键列在未签名的情况下,增加的整数 2.检查的unsigned()

1
Schema::create('cb_category', function (Blueprint $table) { 
     $table->increments('id')->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'); 
    }); 

拼写试试这个

+0

这与问题中的问题相同。创建表时不能引用表,因为表在创建时不存在引用, – Jason