我首先创建了这样的迁移:
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");
});
然后我想将nullable属性添加到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');
});
但我收到了这个错误:
Cannot change column 'user_id': used in a foreign key constraint 'table1_user_id_foreign'
答案 0 :(得分:2)
1-删除您的外键
$table->dropForeign('table1_user_id_foreign');
2-更改user_id列定义:
//If user_id is not unsigned remove unsigned function
$table->integer('user_id')->nullable()->unsigned()->change();
3-创建索引
$table->foreign('user_id')->references('id')->on('users');
完成迁移:
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 :(得分:1)
1。您需要先删除约束:
$table->dropForeign(['user_id']);
2. 或者您可以暂时禁用FK约束:
Schema::disableForeignKeyConstraints();
然后启用约束:
Schema::enableForeignKeyConstraints();
https://laravel.com/docs/5.5/migrations#foreign-key-constraints
答案 2 :(得分:0)
始终在迁移中使用这些代码:
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('table');
Schema::enableForeignKeyConstraints();
}