SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint Laravel

后端 未结 3 1245
半阙折子戏
半阙折子戏 2020-12-28 18:25

Im trying to create a foreign keys using artisan, but this error show up.

[Illuminate\\Database\\QueryException]                                         


        
3条回答
  •  情深已故
    2020-12-28 19:03

    Looks like this was not the problem for you, but I arrived at this same error in Laravel 5.8 and found an interesting issue: Laravel now defaults the 'id' column to 'bigIncrements' instead of just 'increments'. So instead of referencing it with 'integer' like before, you have to reference it with 'bigInteger'.

    If your parent table looks like this:

    $table->bigIncrements('id');
    

    Then the child migration needs to look like this:

    $table->bigInteger('parent_id')->unsigned()->index();
    $table->foreign('parent_id')->references('id')->on('parent');
    

    Hopefully this helps anyone else encountering this problem in 5.8 and beyond.

提交回复
热议问题