繁体   English   中英

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

[英]How to set a foreign key to nullable in Laravel

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

当我运行此迁移时

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

我得到一个错误

[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)

您需要先删除FK约束:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM