简体   繁体   中英

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.

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

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 .

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM