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

后端 未结 22 913
有刺的猬
有刺的猬 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:54

    I had to face the same problem at Larvel 6. I solve this following way.

    I think it helps you or others:

    $table->increments('id');
        $table->bigInteger('user_id')->unsigned(); //chnage this line
        $table->bigInteger('category_id')->unsigned(); //change this line
        ---
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
        $table->foreign('category_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
    

    Incrementing ID using a "big integer" equivalent.

    used bigInteger instead of Integer

    1. If still now you got an error.

    I suggest you reorder your migration file following ways:

    Change the dates that form the first part of the migration filenames So they're in the order you want (example: for 2020_07_28_133303_update_categories.php, the date & time is 2020-07-28, 13:33:03);

    N.B: First must be 'categories' migration file than 'meals' migration File.

提交回复
热议问题