Laravel 迁移更改列的默认值

2022-01-23 00:00:00 migration php laravel laravel-artisan

我有一个已经分配了默认值的表.例如,我们可以查看以下内容:

I have a table with a default value already assigned. For an example we can look at the following:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->integer('active')->default(1);
        });

我现在想更改活动字段的默认值.我期待做这样的事情:

I now want to change my default value on the active field. I am expecting to do something like this:

if (Schema::hasTable('users')) {
        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'active')) {
                $table->integer('active')->default(0);
            }
        });
    }

但它当然告诉我该列已经存在.如何在不删除列的情况下简单地更新列 x 的默认值?

But of course it tells me the column is already there. How can I simply update the default value of column x without dropping the column?

推荐答案

你可以使用 change() 方法:

You can use change() method:

Schema::table('users', function ($table) {
    $table->integer('active')->default(0)->change();
});

然后运行 ​​migrate 命令.

Then run migrate command.

更新

对于 Laravel 4,使用如下内容:

For Laravel 4 use something like this:

DB::statement('ALTER TABLE `users` CHANGE COLUMN `active` `active` INTEGER NOT NULL DEFAULT 0;');

up() 方法中,而不是 Schema::table(); 子句.

Inside up() method instead of Schema::table(); clause.

相关文章