简体   繁体   中英

set existing foreign key column to nullable in alter table migration

I first created a migration like this:

Schema::create('table1',function(Blueprint $table){
        $table->bigIncrements('id');
        $table->string('name')->unique();
        $table->integer("user_id")->unsigned();
        $table->foreign("user_id)->references("id")->on("users");
});

Then i wanted to add nullable property to user_id column , i wrote this migration:

Schema::table('f_subjects', function (Blueprint $table) {
        $table->integer('user_id')->nullable()->change();
        $table->foreign('original_law_id')->references('id')->on('f_original_law');
    });

But i got this error:

Cannot change column 'user_id': used in a foreign key constraint 'table1_user_id_foreign'

1- Delete your foreign key

$table->dropForeign('table1_user_id_foreign');

2- Change user_id column definition:

//If user_id is not unsigned remove unsigned function
$table->integer('user_id')->nullable()->unsigned()->change();   

3- Create index

$table->foreign('user_id')->references('id')->on('users');

Complete migration:

Schema::table('table1',function(Blueprint $table){
    //Or disable foreign check with: 
    //Schema::disableForeignKeyConstraints();
    $table->dropForeign('table1_user_id_foreign');
    $table->integer('user_id')->nullable()->unsigned()->change();
    //Remove the following line if disable foreign key
    $table->foreign('user_id')->references('id')->on('users');
});

1. You need to drop the constraint first:

$table->dropForeign(['user_id']);

2. Or you could temporarily disable FK constraints:

Schema::disableForeignKeyConstraints();

And then enable constraints:

Schema::enableForeignKeyConstraints();

https://laravel.com/docs/5.5/migrations#foreign-key-constraints

Always use these codes in migrations:

 public function down()
    {

        Schema::disableForeignKeyConstraints();
        Schema::dropIfExists('table');
        Schema::enableForeignKeyConstraints();
    }

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