Symfony2 Doctrine ManyToOne依赖所有者

时间:2012-08-11 12:02:00

标签: orm doctrine

我有一个名字和姓氏的User对象。用户可以设置为鬼。如果User是ghost,我想让其他用户可以根据自己的喜好给他命名。

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

ownerghost参考User
owner始终是登录用户

我想要实现的是 - 如果用户不是鬼 - (作为所有者)我想看{4}}和User.name但是如果用户是鬼 - (作为所有者)我想看到User.surnameRepresentation.name

如何使这种情况的映射最有效?

修改 还有什么 - 我有一个关于对象的关联对象,使用Representaion.surname我想看看用户是鬼的正确名称和姓氏。

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

1 个答案:

答案 0 :(得分:0)

您应该像设计两个表一样进行:与幽灵上的用户和表示形成OneToMany关系,与用户和所有者建立另一个OneToMany关系。

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

然后,只做一个->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();
}