php Laravel 迁移更改列的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37003469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:01:42  来源:igfitidea点击:

Laravel migrations change default value of column

phplaravelmigrationartisan

提问by Brendan Van Der Merwe

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);
            }
        });
    }

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?

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

回答by Alexey Mezenin

You can use change()method:

您可以使用change()方法:

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

Then run migratecommand.

然后运行migrate命令。

Update

更新

For Laravel 4 use something like this:

对于 Laravel 4,请使用以下内容:

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

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

内部up()方法而不是Schema::table();子句。

回答by Jerodev

You have to call the change functionto update the column

您必须调用更改函数来更新列

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

回答by Yasin Patel

Create new migration file. and use change()

创建新的迁移文件。并使用change()

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

And also be sure to add the doctrine/dbaldependency to your composer.json file

并且还要确保将doctrine/dbal依赖项添加到您的 composer.json 文件中