[英]How to set a foreign key to nullable in Laravel
I have a user_id set in log table and now have a problem that I sometimes need to store logs to actions performed by non-logged users. 我在日志表中设置了一个user_id,但现在遇到了一个问题,有时我需要将日志存储到非日志记录用户执行的操作中。
When I run this migration 当我运行此迁移时
Schema::table('users_log', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable()->change();
});
I get an error 我得到一个错误
[Illuminate\\Database\\QueryException] SQLSTATE[HY000]: General error: 1832 Cannot change column 'user_id': used in a foreign key constraint 'users_log_user_id_foreign' (SQL: ALTER TABLE users_log CHANGE user_id user_id INT UNSIGNED DEFAULT NULL) [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)
You need to drop FK constraint first: 您需要先删除FK约束:
$table->dropForeign(['user_id']);
Then modify the column and add a new FK constraint. 然后修改列并添加新的FK约束。
Also, make sure you're doing this in a separate Schema::table()
closures. 另外,请确保在单独的Schema::table()
闭包中执行此操作。
https://laravel.com/docs/5.5/migrations#foreign-key-constraints https://laravel.com/docs/5.5/migrations#foreign-key-constraints
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.