如何在Laravel中将外键设置为可为空

nan*_*eri 3 php mysql laravel

我在日志表中设置了一个user_id,现在遇到了一个问题,有时我需要将日志存储到非日志记录用户执行的操作中。

当我运行此迁移时

    Schema::table('users_log', function (Blueprint $table) {
        $table->unsignedInteger('user_id')->nullable()->change();
    });
Run Code Online (Sandbox Code Playgroud)

我得到一个错误

[Illuminate \ Database \ QueryException] SQLSTATE [HY000]:常规错误:1832无法更改列'user_id':用于外键约束'users_log_user_id_foreign'(SQL:ALTER TABLE users_log CHANGE user_id user_id INT UNSIGNED DEFAULT NULL)

Ale*_*nin 6

您需要先删除FK约束:

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

然后修改列并添加新的FK约束。

另外,请确保在单独的Schema::table()闭包中执行此操作。

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