How to change enum type column in laravel migration?

前端 未结 7 2154
挽巷
挽巷 2021-02-05 04:36

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     e         


        
7条回答
  •  醉酒成梦
    2021-02-05 05:10

    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.

提交回复
热议问题