How to make field enum migration yii2

后端 未结 2 1164
忘掉有多难
忘掉有多难 2021-02-12 18:01

I make field ENUM and the result is error when I use yii migrate/up on CMD windows.

public function up()
{
    $tableOptions = null;
    if ($this-&         


        
相关标签:
2条回答
  • 2021-02-12 18:37

    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.
    0 讨论(0)
  • 2021-02-12 18:43

    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

    0 讨论(0)
提交回复
热议问题