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

标签 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");
});

然后我想向 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'

最佳答案

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

关于php - 在更改表迁移中将现有外键列设置为可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48188202/

相关文章:

php - Laravel (OOP),模型特定值数组(例如用户头衔)

php - "Type error: Too few arguments to function App\Http\Controllers\UserController::create(), 0 passed and exactly 1 expected"

PHP 计数 JSON 数组

php - Laravel 5.2 中使用 orWhere 查询范围

php - 使用 Laravel 在 Azure 中来自单个请求的多个重复 HTTP 请求/查询

php - 我在迁移表时遇到问题。这个问题如下

php - 如何在 Laravel 5 中加入模型?

php - 无法向服务器发送 GET/POST 请求

php - 在 <loc> 标记、站点地图索引文件中包含查询的 URL

mysql - Laravel 选择左连接查询