【问题标题】:Doctrine ODM MongoDB - Replicate a simple One to Many Reference with ConstraintDoctrine ODM MongoDB - 使用约束复制简单的一对多引用
【发布时间】:2012-05-07 12:53:40
【问题描述】:

我是 Doctrine、mongo 和 ODM 设置的新手,在 ZF1 中使用此设置时,我试图复制一个带有约束的简单一对多引用。情况如下,希望对如何实现这一点提出一些建议。

这是一个简单的 user->role 映射,所以在 sql 情况下我会有如下表:

用户 - ID - 姓名 - role_id 角色 - ID - 姓名

然后将在用户 role_id 上设置外键约束以映射到角色 id。并且在删除角色时,将触发外键约束来停止操作。

如何在 Doctrines MongoDB ODM 中实现相同的目标?

到目前为止,我已经在 User 实体上使用了不同类型的注释,包括具有不同级联选项的 @ReferenceOne @ReferenceMany...

现在留给我的选择是在“角色”实体上实现@PreUpdate、@PreRemove 生命周期事件,然后检查是否没有用户正在使用该角色,如果他们在更新时将引用更改为匹配或删除抛出异常。

我是在这里还是迷路了?

谢谢,

【问题讨论】:

    标签: php zend-framework doctrine doctrine-orm doctrine-odm


    【解决方案1】:

    对于这样的事情,我不会像在 SQL 中那样拥有两个单独的“表”。您只需将角色类型作为用户的属性。然后,如果您想删除某个角色类型,您只需操作所有具有该角色的用户的角色字段即可。

    但要回答你的问题,我会这样做。

    <?php
    class User {
        /** @MongoDB\Id */
        protected $id;
        /** @MongoDB\String */
        protected $name;
        /** @MongoDB\ReferenceOne(targetDocument="Role", mappedBy="user") */
        protected $role;
    
        //Getters/Setters
    }
    
    class Role {
        /** @MongoDB\Id */
        protected $id;
        /** @MongoDB\String */
        protected $name;
        /** @MongoDB\ReferenceMany(targetDocument="User", inversedBy="role") */
        protected $users;
    
        public function _construct() {
            $this->users = new Doctrine\Common\Collections\ArrayCollection;
        }
        // Getters/Setters
    
        public function hasUsers() {
            return !$this->users->isEmpty();
        }
    }
    

    然后我会创建一个服务类来使用我的文档管理器。

    class RoleService {
        public function deleteRole(Role $role) {
            if (!$role->hasUsers()) {
                // Setup the documentManager either in a base class or the init method. Or if your über fancy and have php 5.4, a trait.
                $this->documentManager->remove($role);
                // I wouldn't always do this in the service classes as you can't chain
                // calls without a performance hit.
                $this->documentManager->flush();
            }
        }
    }
    

    【讨论】:

    • 没问题。在开始使用 Doctrine 时,我经历了和你一样的痛苦。一旦你掌握了它,那就太棒了!
    • 我认为到目前为止它真的很好。它使在顶层构建服务层变得更加容易。一点是我 Roles::hasUsers() 应该返回 !$this->users->isEmpty();反转布尔值。非常感谢您的帮助,这就像做梦一样。
    猜你喜欢
    • 2012-04-12
    • 2023-03-23
    • 1970-01-01
    • 2013-07-31
    • 2016-06-26
    • 2015-04-10
    • 1970-01-01
    • 2011-12-28
    • 2012-12-20
    相关资源
    最近更新 更多