How to make yii2 field enumeration migration

I create an ENUM field and the result is an error when I use yii migrate/up in CMD windows.

 public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('{{%user_social_media}}', [ 'social_media' => $this->ENUM('facebook', 'google', 'twitter', 'github'), 'id' => $this->primaryKey(), 'username' => $this->string(), 'user_id' => $this->integer(11), 'created_at' => $this->integer(11), 'updated_at' => $this->integer(11), ], $tableOptions); } 

When I migrate / up error

+15
enums migration yii yii2 data-migration
source share
2 answers

There is currently no enum () method, because not every database supports ENUM fields. You can do it manually though:

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

Note: This solution is only for mysql.

For relevant Postgresql content, visit here.

+34
source share

Actually the best way to do this and keep the migrations clean is to use some kind of tool / helper similar to the one provided by the yii2mod team https://github.com/yii2mod/yii2-enum

that way you can build enum functionality on code that works like a charm.

i.e. enumeration for gender type

 <?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 instance of the type using the name value.
  • getValueByName () - returns a constant key by value (label)
  • createByValue () - creates a new instance of the type using the value.
  • listData () - returns an associative array with constant and label values
  • getLabel () - returns a constant label by key
  • getConstantsByName () - returns a list of constants (by name) for this type.
  • getConstantsByValue () - returns a 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.
+1
source share

All Articles