How to change enum type column in laravel migration?

妖精的绣舞 提交于 2019-12-18 14:06:10

问题


I am using Laravel 5.1 and I have a table called packages with this structure:

id              int(11)
weight          decimal(10,2)           
weight_unit     enum('Kg.', 'Gm.')

I would like to change the weight_unit enum to:

weight_unit enum('Grams','Kgs.','Pounds')

For this I create the following migration:

public function up()
{
    Schema::table('packages', function ($table) {
        $table->enum('weight_unit', array('Grams','Kgs.','Pounds'))->nullable()->change();
    });
}

But when I run the migration I receive an error:

Unknown database type enum requested, Doctrine\DBAL\Platforms\MySqlPlatform  

may not support it.

How can I change this enum?


回答1:


Use the DB::statement method:

DB::statement("ALTER TABLE packages MODIFY COLUMN weight_unit ENUM('Grams', 'Kgs', 'Pounds')");



回答2:


This worked for me when adding a new enum value to the modified enum column.

Add the following to the up() method:

DB::statement("ALTER TABLE packages MODIFY weight_unit ENUM('Grams', 'Kgs', 'Pounds', 'new value') NOT NULL");

Then in the down() method you can revert the change that was made:

DB::statement("ALTER TABLE packages MODIFY weight_unit ENUM('Grams', 'Kgs', 'Pounds') NOT NULL");

Note: before the enum value is removed it needs to be changed to another enum value that will be retained.




回答3:


You can add custom constructor to migration and explain to Doctrine that enum should be treated like string.

public function __construct(\Doctrine\DBAL\Migrations\Version $version)
{
    parent::__construct($version);

    $this->platform->registerDoctrineTypeMapping('enum', 'string');
}



回答4:


$table->enum('level', ['easy', 'hard']);



回答5:


In case you dont want to lose your data and update it with the new values I came up with this solution:

// Include old and new enum values
DB::statement("ALTER TABLE packages MODIFY COLUMN weight_unit ENUM('Kg.', 'Gm.', 'Grams', 'Kgs', 'Pounds')");
// Replace Kg. with Kgs
Packages::where('weight_unit', 'Kg.')->update(['weight_unit' => 'Kgs']);
// Replace Gm. with Grams
Packages::where('weight_unit', 'Gm.')->update(['weight_unit' => 'Grams']);
// Delete old values
DB::statement("ALTER TABLE packages MODIFY COLUMN weight_unit ENUM('Grams', 'Kgs', 'Pounds')");

This way you can replace your old values with the new ones.




回答6:


add this before change() call :

DB::getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');


来源:https://stackoverflow.com/questions/33496518/how-to-change-enum-type-column-in-laravel-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!