Doctrine2:动态实体关联,许多targetEntity由一个字段映射

时间:2012-03-28 22:59:38

标签: php symfony doctrine doctrine-orm

我有一个名为Event的实体

  • 字段“associatedEntity”,其中包含Bundle中其他实体的类名
  • 该特定“associatedEntity”实体的字段“targetId”

我现在想以某种方式访问​​我的Event-Entity中的这个目标实体,但我现在确定如何做到这一点。我想使用像

这样的东西来访问树枝模板中的不同目标实体
{% if event.getClassName() == "User" %}
  {{ if event.getUser().getName() }}
{% endif %}

编辑:为了清楚起见,目前我唯一感兴趣的是如何正确地建立关系。在ORM世界之外,您可能会使用连接语句。就好像我有一个由一个字段映射的目标实体。

到目前为止,我使用实体存储库和DI加载相关的实体,但我发现丑陋知道我可以使用JOIN语句:

public function getUpcomingEvents(){
        $query = $this->createQueryBuilder('E')
        ->where('E.resolved = false')
        ->orderBy('E.notify_date', 'ASC')
        ->setMaxResults( $limit );
    $res = $query->getQuery()->getResult();
    $res = $this->attachAssociatedObjects($res);
    return $res;
}

public function attachAssociatedObjects($res){
    foreach ($res as $key => $entity) {
            $assocObject = $this->getEntityManager()->getReference('My\Bundle\Entity\\'.$entity->getClassName(), $entity->getTargetId());
            $res[$key]->setAssociatedObject($assocObject);
    }
    return $res;
}

1 个答案:

答案 0 :(得分:1)

Twig attribute function就是您所需要的。