Doctrine ODM MongoDB - 使用约束复制简单的一对多引用


Doctrine ODM MongoDB - Replicate a simple One to Many Reference with Constraint

我是教义、mongo 和 ODM 设置的新手,在 ZF1 中使用此设置时,我正在尝试使用约束复制一个简单的一对多引用。 这是情况,并希望就如何实现这一目标提供一些建议。

这是一个简单的用户>角色映射,因此在 sql 情况下,我将具有如下表:

用户 - 编号 -名字 - role_id角色 - 编号 -名字

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

我怎样才能在Doctrines MongoDB ODM中实现相同的目标?

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

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

我在这里还是迷路了?

谢谢

对于这样的事情,我不会像在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();
        }
    }
}