简体   繁体   中英

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

I have table migration like this. I want to change the column from nullable to set default 0.

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

But, when I am create migration to change the column from nullable to set default 0 like this. Why changed column is still null?

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

How to fix this?

Setting a default does not remove the nullable from the column, this is how you would set a column as not nullable.

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

However this may not automatically set the default values to currently null columns because the default (as far as I know) applies to new inserts only. To fix this you could add this in your migration file before the Schema::table call:

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

however this will result in your migration to not be fully reversible.

In the first migration you have a table called "table". The second migration specifies the name "products".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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