Yii2: Yii 2 does not support ENUMs in migrations?

Created on 30 May 2020  路  6Comments  路  Source: yiisoft/yii2

When I use migrations to create tables, can not use enum column type.
Oh my god!!!

| Q | A
| ---------------- | ---
| Yii version | 2.0.35
| PHP version | 7.3
| Operating system | cent OS 7

Most helpful comment

There is no enum() method at the moment since not every DB is supporting ENUM fields.

All 6 comments

What problem you have to use enum column type?

The migrate tools does not support 'enum' directly, or a few other column definitions. A list of supported schema types. My understanding is that the trait attempts to provide a database agnostic implementation.

A technique using SQL string may help you. Try including something like the following snippet as part of the column description array.

$this->createTable(
            '{{%mytablename}}',
            [
// columns
'honorific' => "enum('Mr', 'Mrs', 'Ms', 'Miss', 'Dr', 'Prof') NOT NULL",
//more columns
],

There is no enum() method at the moment since not every DB is supporting ENUM fields.

I usually write create table migration using sql code. Then, you can specify database differences updated $sql var.

This is an example:

<?php

use yii\db\Migration;

class m200528_144124_create_table_mysql extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {

        $sql = <<< EOT_SQL
        CREATE TABLE `mytable` (
            `honorific` enum('Mr', 'Mrs', 'Ms', 'Miss', 'Dr', 'Prof') NOT NULL
          );
EOT_SQL
        ;

        if ($this->db->driverName === 'pgsql') {
            // Specific code for postgresql
            $sql = "...";
        }


        \Yii::$app->db->createCommand($sql)->execute();


    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('mytable');
    }
}

thx every body, That sounds like a pity.

As @Thoulah mentioned, it's impossible to add enums for every possible DB and as @FabrizioCaldarelli posted, it's possible to do it with SQL.

Closing the ticket since we can't fix that.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chaintng picture chaintng  路  3Comments

Locustv2 picture Locustv2  路  3Comments

nokimaro picture nokimaro  路  3Comments

newscloud picture newscloud  路  3Comments

schmunk42 picture schmunk42  路  3Comments