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

最佳答案

使其为unsignednullable

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

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');

});

08-26 18:47