首页 > 解决方案 > 在 Laravel 中更改 ENUM 列并为该列添加值

问题描述

我有一个MySQL数据库,其中有一个名为 user_level_attempt 的表。该表有一个带有['PROGRESSED', 'STOPPED', 'COMPLETED']值的ENUM类型列。我需要编写迁移以向该列添加另一个值(比如说“通过”)。添加后,它看起来像这样,['PROGRESSED', 'STOPPED', 'COMPLETED', 'PASSED]。我怎么能在 Laravel 中做到这一点?我尝试了以下解决方案,但它似乎不是一个好的做法/解决方案。

 /**
         * Schema table name to migrate
         * @var string
         */
        public $set_schema_table = 'bt_user_level_attempt';


        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::table($this->set_schema_table, function ($table) {
                $table->dropColumn('status');
            });

            Schema::table($this->set_schema_table, function ($table) {
                $table->enum('status', ['PROGRESS', 'STOPPED', 'COMPLETED', 'PASSED'])->default('PROGRESS')->after('effective_time_spend');
            });
        }

/**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table($this->set_schema_table, function ($table) {
            $table->dropColumn('status');
        });

        Schema::table($this->set_schema_table, function ($table) {
            $table->enum('status', ['PROGRESS', 'STOPPED', 'COMPLETED'])->default('PROGRESS')->after('effective_time_spend');
        });
    }

谢谢你。

标签: phplaravelenumseloquentdatabase-migration

解决方案


毕竟,我想找到解决办法。感谢所有给我启发的小伙伴。:)

/**
     * Schema table name to migrate
     * @var string
     */
    public $set_schema_table = 'bt_user_level_attempt';


    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("ALTER TABLE ".$this->set_schema_table." MODIFY COLUMN status ENUM('PROGRESS', 'STOPPED', 'COMPLETED', 'PASSED') NOT NULL DEFAULT 'PROGRESS'");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("ALTER TABLE ".$this->set_schema_table." MODIFY COLUMN status ENUM('PROGRESS', 'STOPPED', 'COMPLETED') NOT NULL DEFAULT 'PROGRESS'");
    }

推荐阅读