簡體   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