errno: 150 “外键约束的格式不正确”但检查我知道的一切

问题

运行迁移时,最后一个表以标题中的错误结束。

我的数据库是本地 MySQL。

错误

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table shopping_list_develop#sql-1698_2b(errno: 150 "外键约束形成不正确") (SQL: alter table productsadd constraintproducts_shopping_list_id_foreign外键 ( shopping_list_id) 引用shopping_listsid) on delete set null on update cascade)

已经试过了

这是我检查的内容:

  • 父表 ( shopping_lists) 在子表 ( products)之前创建。

  • 外键shopping_list_id与它引用的列的类型相同。

  • 这两个表,shopping_listsproducts具有相同的数据库引擎(InnoDB)。

我已阅读其他答案,但找不到解决方案。

迁移

2019_05_13_192170_create_shopping_lists_table.php

<?php


use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Carbon\Carbon;


class CreateShoppingListsTable extends Migration {


    public function up()

    {

        Schema::create('shopping_lists', function(Blueprint $table) {

            $table->bigIncrements('id');

            $table->string('name')->nullable()->default(Carbon::now()->toDateString());

            $table->unsignedBigInteger('user_id');

            $table->timestamps();


            $table->foreign('user_id')->references('id')->on('users')

                        ->onDelete('cascade')

                        ->onUpdate('cascade');

        });

    }


    public function down()

    {

        Schema::table('shopping_lists', function(Blueprint $table) {

            $table->dropForeign(['user_id']);

        });

        Schema::dropIfExist('shopping_lists');

    }

}


慕娘9325324
浏览 152回答 1
1回答

皈依舞

在您的2019_05_13_192700_create_products_table.php迁移中, onDelete 您将值设置为 null。$table->foreign('shopping_list_id')->references('id')->on('shopping_lists') &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;->onDelete('set&nbsp;null') &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;->onUpdate('cascade');但是您声明的列不可为空$table->unsignedBigInteger('shopping_list_id');尝试通过执行以下操作使该列可以为空:$table->unsignedBigInteger('shopping_list_id')->nullable();
打开App,查看更多内容
随时随地看视频慕课网APP