Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make field enum migration yii2

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->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

like image 318
CrashBurn Avatar asked Aug 23 '16 16:08

CrashBurn


2 Answers

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

like image 149
Bizley Avatar answered Sep 29 '22 03:09

Bizley


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.
like image 37
Pablo Palacios Avatar answered Sep 29 '22 05:09

Pablo Palacios