gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:28:17 25 4
gpt4 key购买 nike

尝试在项目表的“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com