簡體   English   中英

成功將列從可空更改為設置默認值,但值仍然是 null

[英]Successfully change column from nullable to set default, but the value is still null

我有這樣的表遷移。 我想將列從可為空更改為設置默認值 0。

        Schema::create('table', function (Blueprint $table) {
            ...
            $table->integer('sold_count')->nullable();
            $table->integer('view_count')->nullable();
            ...
        });

但是,當我創建遷移以將列從可為空更改為像這樣設置默認值 0 時。 為什么更改的列仍然是 null?

        Schema::table('table', function (Blueprint $table) {
            $table->integer('sold_count')->default(0)->change();
            $table->integer('view_count')->default(0)->change();
        });

如何解決這個問題?

設置默認值不會從列中刪除可為空的,這就是您將列設置為不可為空的方式。

Schema::table('table', function (Blueprint $table) {
    $table->integer('sold_count')->nullable(false)->default(0)->change();
    $table->integer('view_count')->nullable(false)->default(0)->change();
});

但是,這可能不會自動將默認值設置為當前 null 列,因為默認值(據我所知)僅適用於新插入。 要解決此問題,您可以在Schema::table調用之前將其添加到遷移文件中:

DB::table('table')->whereNull('sold_count')->update([ 'sold_count' => 0 ]);
DB::table('table')->whereNull('view_count')->update([ 'view_count' => 0 ]);

但是,這將導致您的遷移不完全可逆。

在第一次遷移中,您有一個名為“table”的表。 第二個遷移指定名稱“產品”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM