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