mysql - 无法更改表以添加外键?

标签 mysql laravel

尝试在项目表的“member_id”列上添加外键,该列引用成员表上的主键“id”。

项目迁移

Schema::create('projects', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->text('title');
            $table->text('description');

            $table->timestamps();
        });

成员迁移

Schema::create('members', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('country_id');
            $table->string('name');
            $table->string('email');
            $table->integer('active');
            $table->timestamps();
        });

AddMemberIdToProjects 迁移

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

            $table->unsignedBigInteger('member_id');

            $table->foreign('member_id')->references('id')->on('members');

        });
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails 

最佳答案

使其无符号可空

单独创建列和添加外键逻辑以避免类似错误:

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

   $table->unsignedBigInteger('member_id')->nullable();
});

Schema::table('projects', function (Blueprint $table) {
   $table->foreign('member_id')->references('id')->on('members');

});

关于mysql - 无法更改表以添加外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59223274/

相关文章:

mysql - 如何创建一个 MYSQL 触发器,在更新另一个具有该产品多个实例的表时更新该产品的库存水平?

c++ - 多线程环境下MySQL C++ Connector的使用

php - Laravel 5.2 : Do something after user has logged in?

php - 导出为 csv 时不计算公式

php - Ajax 检索错误无法正常工作 Laravel

php/mysql 多选困境

mysql - 如何将surveyjs库连接到数据库(Mysql)

php - 计算菜单项返回的行数

php - 在 null 上调用成员函数 comments()

jquery 表单过滤器在每次选择后不会重置