Laravel 迁移 - 更新枚举选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25251186/
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-09-08 16:41:33  来源:igfitidea点击:

Laravel Migration - Update Enum Options

laravel

提问by Lisa

I'm trying to add an enum option to a table (without losing the current dataset) using the schema builder.

我正在尝试使用模式构建器向表添加枚举选项(不丢失当前数据集)。

The only thing I've really been able to find about column alteration is http://www.flipflops.org/2013/05/25/modify-an-existing-database-column-in-a-laravel-migration/and I believe that was written for Laravel3.

我真正能够找到关于列更改的唯一一件事是http://www.flipflops.org/2013/05/25/modify-an-existing-database-column-in-a-laravel-migration/和我相信这是为 Laravel3 编写的。

Even so, I tried using the DB::query('ALTER TABLE ...'); command but it errored out with call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'query'.

即便如此,我还是尝试使用 DB::query('ALTER TABLE ...'); 命令但它出错了 call_user_func_array() 期望参数 1 是一个有效的回调,类 'Illuminate\Database\MySqlConnection' 没有方法 'query'。

DB::query("ALTER TABLE users CHANGE COLUMN permissions permissions ENUM('admin', 'user', 'candidate')");

I also tried doing this:

我也试过这样做:

Schema::table('users', function ($table) {
    $table->enum('permissions', array('admin', 'user', 'candidate'))->default('user');
});

but it errors out saying the column already exists.

但它出错说该列已经存在。

What's the best way to do what I'm trying to do without losing all the data in that column?

在不丢失该列中的所有数据的情况下做我想做的事情的最佳方法是什么?

回答by Joseph Silber

Use the DB::statementmethod:

使用DB::statement方法:

DB::statement("ALTER TABLE users CHANGE COLUMN permissions permissions ENUM('admin', 'user', 'candidate') NOT NULL DEFAULT 'user'");

回答by Vazgen

Modifying Columns

修改列

Prerequisites

先决条件

Before modifying a column, be sure to add the?doctrine/dbal?dependency to your?composer.json?file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column:

在修改列之前,请务必将?doctrine/dbal?dependency 添加到您的?composer.json? 文件中。Doctrine DBAL 库用于确定列的当前状态并创建对列进行指定调整所需的 SQL 查询:

Schema::table('users', function (Blueprint $table) { 
    $table->enum('name', [])->change(); 
});

https://laravel.com/docs/5.8/migrations#modifying-columns

https://laravel.com/docs/5.8/migrations#modifying-columns