在更改表迁移中将现有外键列设置为可为空

sa-*_*-fm 4 php laravel

我首先创建了这样的迁移:

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");
});
Run Code Online (Sandbox Code Playgroud)

然后我想向 user_id 列添加可空属性,我写了这个迁移:

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

但我收到了这个错误:

Cannot change column 'user_id': used in a foreign key constraint 'table1_user_id_foreign'
Run Code Online (Sandbox Code Playgroud)

Ale*_*nin 6

1.需要先删除约束:

$table->dropForeign(['user_id']);
Run Code Online (Sandbox Code Playgroud)

2.或者您可以暂时禁用 FK 约束:

Schema::disableForeignKeyConstraints();
Run Code Online (Sandbox Code Playgroud)

然后启用约束:

Schema::enableForeignKeyConstraints();
Run Code Online (Sandbox Code Playgroud)

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


ram*_*esh 6

1-删除您的外键

$table->dropForeign('table1_user_id_foreign');
Run Code Online (Sandbox Code Playgroud)

2- 更改 user_id 列定义:

//If user_id is not unsigned remove unsigned function
$table->integer('user_id')->nullable()->unsigned()->change();   
Run Code Online (Sandbox Code Playgroud)

3- 创建索引

$table->foreign('user_id')->references('id')->on('users');
Run Code Online (Sandbox Code Playgroud)

完整迁移:

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');
});
Run Code Online (Sandbox Code Playgroud)