[英]cannot alter a table to add foreign key?
Trying to add foreign key on column 'member_id' of projects table which references on primary key 'id' on members table.尝试在项目表的“member_id”列上添加外键,该表引用成员表上的主键“id”。
Projects Migration项目迁移
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('title');
$table->text('description');
$table->timestamps();
});
Members migration会员迁移
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 migration 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
Make it unsigned
and nullable
.使其unsigned
和nullable
。
Separate creating a column and adding foreign key logic to avoid similar errors:分开创建列和添加外键逻辑,避免类似错误:
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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.