What do you use instead of ENUM in doctrine2?

后端 未结 4 1749
半阙折子戏
半阙折子戏 2021-01-30 13:04

What do you use instead of ENUM in Doctrine2? smallint? I thought of using varchar, or explicitly define char, but this may not be very effective when it comes to indexes, or am

4条回答
  •  借酒劲吻你
    2021-01-30 13:51

    If you want MySQL ENUMs using MySQL and Symfony, you can now use an easy way for that without any dependencies

    use a base class for all enums:

    values);
    
            return "ENUM(".implode(", ", $values).")";
        }
    
        public function convertToPHPValue($value, AbstractPlatform $platform)
        {
            return $value;
        }
    
        public function convertToDatabaseValue($value, AbstractPlatform $platform)
        {
            if (!in_array($value, $this->values)) {
                throw new \InvalidArgumentException("Invalid '".$this->name."' value.");
            }
            return $value;
        }
    
        public function getName()
        {
            return $this->name;
        }
    
        public function requiresSQLCommentHint(AbstractPlatform $platform)
        {
            return true;
        }
    }
    

    extend it for your special case:

    namespace App\Enum;
    
     class UploadFileStatusType extends EnumType
    {
         const OPEN = 'open';
         const DONE = 'done';
         const ERROR = 'error';
    
         protected $name = self::class;
    
         protected $values = [
             self::OPEN => self::OPEN ,
             self::DONE => self::DONE,
             self::ERROR => self::ERROR,
         ];
    
    }
    

    add it to your dcotrine.yml config file:

    doctrine:
        dbal:
            types:
                UploadFileStatusType: App\Enum\UploadFileStatusType
    

    use it in your entity file as doctrine column doc type:

    class MyEntity
    {
        /**
         * @var string
         *
         * @ORM\Column(type="UploadFileStatusType")
         */
        protected $status;
    }
    

    And you will end up with a clean MySQL ENUM type for column status:

    enum('open', 'done', 'error')
    

提交回复
热议问题