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) references
cb_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.
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
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()
Try this