【问题标题】:Symfony2 & Doctrine2 - automatically insert/update key-value rowsSymfony2 & Doctrine2 - 自动插入/更新键值行
【发布时间】:2014-09-09 19:30:52
【问题描述】:

我正在使用 Doctrine 学习 Symfony2,所以我是新手。 这是我的问题:我有带有“statusId”列的用户表(只是示例,更像我的项目中的那个)。我还有带有“id”和“name”列的 DictStatus 表(id​​ => name == key => value)。是否可以在学说 2 中向我的 DictStatus 映射添加一些常量(例如:const ACTIVE = 1;),以便将其作为 id='1' 和 name='ACTIVE' 的行自动插入或更新到数据库中?

如果这是不可能的,我可以使用http://php.net/manual/en/reflectionclass.getconstants.php 提取常量,准备插入并自动运行我的脚本 学说:模式:更新--force

或者不使用 DictTable 并将我的状态仅硬编码为常量怎么办?那会是不雅的还是什么的;)?

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    如果状态只是一个标量值,我建议不要为其创建单独的实体。这将在以后为您节省大量的数据库查询。最有效的方法是将其作为整数处理。

    如果您觉得常量更安全,可以将它们实现为实体类的属性。

    <?php
    
    namespace Your\SomethingBundle\Entity;
    
    use \Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity
     */
    class Foobar
    {
        const STATUS_GREAT = 1;
        const STATUS_NOTSOGREAT = 0;
    
        /**
         * @ORM\Column(type="integer")
         */
        protected $status;
    
    
        public function setStatus($status)
        {
            $this->status = $status;
        }
    }
    

    使用示例:

    $myFoobar = new Foobar();
    $myFoobar->setStatus(Foobar::STATUS_GREAT);
    

    $status 值的验证可以在 setter 本身或通过 Validator annotation 完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      相关资源
      最近更新 更多