Laravel migration: “Foreign key constraint is incorrectly formed” (errno 150)

后端 未结 22 715
有刺的猬
有刺的猬 2020-11-30 07:21

When migrating my DB, this error appears. Below is my code followed by the error that I am getting when trying to run the migration.

Code



        
相关标签:
22条回答
  • 2020-11-30 07:48

    I just use $table->unsignedBigInteger('user_id'); and solve it . (laravel 5.8)

    0 讨论(0)
  • 2020-11-30 07:48

    It is a simple question, so give a simple answer and stop beating about the bush, change your example $table->integer('user_id')->unsigned(); to $table->BigInteger('user_id')->unsigned(); to solve the foreign key error. so change integer to BigInteger in the migration file...

    0 讨论(0)
  • 2020-11-30 07:49
    1. Check in your database reference table must have primary key && auto increment
    2. Drop the table which you want to migrate and Run the migrate again
    0 讨论(0)
  • 2020-11-30 07:50

    Maybe it can be of help to anyone landing here : I just experienced this same issue, and in my case it was that I had a (composite) unique constraint set on the foreign key column BEFORE the foreign key constraint. I resolved the issue by having the "unique" statement placed AFTER the "foreign" statement.

    Works:

    $table->foreign('step_id')->references('id')->on('steps')->onDelete('cascade');
    $table->unique(['step_id','lang']);
    

    Doesn't work:

    $table->unique(['step_id','lang']);
    $table->foreign('step_id')->references('id')->on('steps')->onDelete('cascade');
    
    0 讨论(0)
  • 2020-11-30 07:52

    For me everything was in correct order, but it still didn't work. Then I found out by fiddling that the primary key must be unsigned.

    //this didn't work
    $table->integer('id')->unique();
    $table->primary('id');
    
    //this worked
    $table->integer('id')->unsigned()->unique();
    $table->primary('id');
    
    //this worked 
    $table->increments('id');
    
    0 讨论(0)
  • 2020-11-30 07:52

    In my case, the new laravel convention was causing this error.

    Just by a simple swap of the table creation id did the trick.

    $table->increments('id'); // ok
    

    , instead of:

    $table->bigIncrements('id'); // was the error.
    

    Already working with Laravel v5.8, never had this error before.

    0 讨论(0)
提交回复
热议问题