从Symfony2和Doctrine2定义和使用ENUM类型的正确方法

Rey*_*ier 5 symfony-forms symfony doctrine-orm symfony-2.3

我在我的一张桌子上使用ENUM类型,但是Doctrine并不喜欢它.所以我做了我的研究,发现这个主题基本上是谈论它.在一篇来自Doctrine项目的文档中,还讨论了它和两种可能的解决方案.我将使用第一个但是:

  1. 假设这个代码应该去哪里?

    $conn = $em->getConnection();
    $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

  2. 当我想要显示带有这些值的SELECT时,如何从Forms中处理这个?

alt*_*aus 5

关于此doc,您需要将这些行添加到您的配置中:

# app/config/config.yml
doctrine:
    dbal:
        connections:
            default:
                // Other connections parameters
                mapping_types:
                    enum: string
Run Code Online (Sandbox Code Playgroud)

对于表单,我会添加一个帮助器,getPossibleEnumValues并使用它来填充构建器中的选项:

$builder->add('enumField', 'choice', array(
    'choices' => $entity->getPossibleEnumValues(),
));
Run Code Online (Sandbox Code Playgroud)


Pie*_*rre 5

你不应该使用枚举(由于很多原因,你可以在谷歌或这里找到),但如果你绝对想要使用枚举而不是与另一个表的关系,最好的方法是模仿这样的枚举行为:

<?php
/** @Entity */
class Article
{
    const STATUS_VISIBLE = 'visible';
    const STATUS_INVISIBLE = 'invisible';

    /** @Column(type="string") */
    private $status;

    public function setStatus($status)
    {
        if (!in_array($status, array(self::STATUS_VISIBLE, self::STATUS_INVISIBLE))) {
            throw new \InvalidArgumentException("Invalid status");
        }
        $this->status = $status;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Aleqxs:实际上,您永远不应该使用ENUM ...除非在某些特殊情况下,例如,如果您使用ENUM来存储一周中几天的值,以帮助人类阅读,那么这是一种有效的用法。但是我更喜欢像上面描述的那样模拟ENUM。 (2认同)