[英]Laravel migrations change default value of column
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 的默认值?
You can usechange()
method:您可以使用
change()
方法:
Schema::table('users', function ($table) {
$table->integer('active')->default(0)->change();
});
Then run migrate
command.然后运行
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();
内部
up()
方法而不是Schema::table();
clause.条款。
You have to call the change function to update the column您必须调用更改函数来更新列
if (Schema::hasTable('users')) {
Schema::table('users', function (Blueprint $table) {
if (Schema::hasColumn('users', 'active')) {
$table->integer('active')->default(0)->change();
}
});
}
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/dbal
dependency to your composer.json file并且还要确保将
doctrine/dbal
依赖项添加到您的 composer.json 文件中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.