How to make field enum migration yii2

Actually the best way of working this and keeping your migrations clean would be by using some tool/helper like the one provided by the yii2mod team https://github.com/yii2mod/yii2-enum

this way you can build the enum functionality on code, works like a charm.

i.e. an enum for genderType

<?php

namespace common\models\enums;

use yii2mod\enum\helpers\BaseEnum;

/**
 * Class GenderType
 *
 * @package yii2mod\settings\models\enumerables
 */
class GenderType extends BaseEnum
{
    // add as many genders as you need
    const MALE_TYPE = 'MALE';
    const FEMALE_TYPE = 'FEMALE';

    public static $list = [
        self::MALE_TYPE => 'Male',
        self::FEMALE_TYPE => 'Female',
    ];
}

Use the following methods to access your Enum:

  • createByName() - Creates a new type instance using the name of a value.
  • getValueByName() - Returns the constant key by value(label)
  • createByValue() - Creates a new type instance using the value.
  • listData() - Returns the associative array with constants values and labels
  • getLabel()- Returns the constant label by key
  • getConstantsByName() - Returns the list of constants (by name) for this type.
  • getConstantsByValue() - Returns the list of constants (by value) for this type.
  • isValidName() - Checks if a name is valid for this type. isValidValue() - Checks if a value is valid for this type.

There is no enum() method at the moment since not every DB is supporting ENUM fields. You can do it manually though:

'social_media' => "ENUM('facebook', 'google', 'twitter', 'github')",

Note: This solution is for Mysql only

For related Postgresql content visit here