如何使字段枚举迁移yii2

y0u0uwnf  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(161)

当我在CMD窗口上使用yii migrate/up时,我生成字段ENUM,结果是错误。

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);
}

q5lcpyga

q5lcpyga1#

目前还没有enum()方法,因为不是每个数据库都支持ENUM字段。您可以手动执行此操作:

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

注意:此解决方案仅适用于Mysql
有关Postgresql的相关内容,请访问here

ajsxfq5m

ajsxfq5m2#

实际上,最好的方法是使用yii 2 mod团队https://github.com/yii2mod/yii2-enum提供的工具/助手来完成这个任务,并保持迁移的干净。
通过这种方式,您可以在代码上构建枚举功能,工作起来非常有魅力。
即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',
    ];
}

使用以下方法访问枚举:

  • createByName()-使用值的名称创建新的类型示例。
  • getValueByName()-按值返回常量键(标签)
  • createByValue()-使用值创建新类型示例。
  • listData()-返回带有常量值和标签的关联数组
  • getLabel()-按键返回常量标签
  • getConstantsByName()-返回此类型的常量列表(按名称)。
  • getConstantsByValue()-返回此类型的常量列表(按值)。
  • isValidName()-检查名称对于此类型是否有效。isValidValue()-检查值对于此类型是否有效。

相关问题