0

我有一个带有姓名和姓氏的用户对象。用户可以设置为幽灵。如果用户是幽灵,我想让其他用户可以随意命名他。

|User   |   |Representation|
|-------|   |--------------|
|ID     |   |owner         |
|isGhost|   |ghost         |
|name   |   |name          |
|surname|   |surname       |

owner并且ghost引用User
owner始终是登录用户

我想要实现的是 - 如果用户不是幽灵 - (作为所有者)我想看到User.nameUser.surname但如果用户是幽灵 - (作为所有者)我想看到Representation.nameRepresentaion.surname.

如何为这种情况进行映射以最有效?

编辑: 还有什么 - 我有一个参考用户的 Relation 对象,并且在 Relation 中使用getUser()我想查看正确的名称和姓氏,具体取决于用户是否是幽灵。

也许使用 ArrayCollection 而不是附加表并将所有表示保存在 ghost User 中?每个幽灵用户的预测最大表示约为 5-10。不多。

4

1 回答 1

0

您应该像设计两个表一样继续操作:OneToMany在 ghost 上建立一个关系 bw User 和 Representation,以及另一个OneToMany关系 bw User 和 Owner。

确保拥有方是用户,因为您不想在每次查询用户时加载表示对象。

然后,仅->getRepresentations()在必要时为用户获取相关表示,例如:当 true === isGhost;

问题是,如果用户是幽灵并且没有所有者的代表,你会显示什么?

你可以做这个功能:

public function getUsername($ownerRepresentation = false)
{

    // user is ghost mode, but we do not have an owner for its representation
    if ($this->isGhost && false === $ownerRepresentation) {
        return '~';
    }

    // user is ghost, and we have provided an owner to search for his representation
    if ($this->isGhost && false !== $ownerRepresentation) {
        $representations = $this->getRepresentations();

        foreach ($representations as $representation) {
            if ($representation->getOwner()->getId() === $ownerRepresentation->getId()) {
                return $representation->getName() . ' ' . $representation->getSurname();
            }
        }

        // no representation found for this owner
        return '~';
    }

    // user is no ghost, we can freely display his real name
    return $this->getName() . ' ' . $this->getSurname();
}
于 2012-08-11T18:21:09.040 回答