Laravel migration self referencing foreign key issue

江枫思渺然 提交于 2019-11-30 09:00:21

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.

I may be too late for the party, but the official docs claim that the foreign key, in case of integer, must be ->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.

Also, Artisan does not fail if you (as I have) misspell unsigned() and I have spent quite a few hours trying to figure out why the key was not created.

So two things: 1. Always make the foreign key column unsigned in case of incrementing integers 2. Check the spelling of unsigned()

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

Try this

Two querys work :

Schema::create('cb_category', function($table)
{
    $table->integer('id')->primary()->unique()->unsigned();
    $table->integer('parent_id')->nullable();  
});

Schema::table('cb_category', function (Blueprint $table) 
{
    $table->foreign('parent_id')->references('id')->on('cb_category')->onUpdate('cascade')->onDelete('cascade');
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!