简体   繁体   English

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

[英]Doctrine2: dynamic entity associations, many targetEntity mapped by one field

I have a Entity called Event which has 我有一个名为Event的实体

  • a field "associatedEntity" containing the class name of another Entity in the Bundle 字段“associatedEntity”,包含Bundle中另一个实体的类名
  • a field "targetId" of that specific "associatedEntity" Entity 该特定“associatedEntity”实体的字段“targetId”

I would now like to access this target entity inside my Event-Entity somehow but im now sure how to do it. 我现在想以某种方式访问​​我的Event-Entity中的这个目标实体,但我现在确定如何做到这一点。 I'd like to access the different target Entities in a twig template using something like 我想使用类似的东西访问树枝模板中的不同目标实体

{% if event.getClassName() == "User" %}
  {{ if event.getUser().getName() }}
{% endif %}

Edit: Just to be clear, the only thing im interested so far is how to create the relation properly. 编辑:为了清楚,到目前为止我唯一感兴趣的是如何正确地创建关系。 Outside a ORM World you would probably use a join statement for this. 在ORM世界之外,您可能会使用连接语句。 It is like i have many target Entities mapped by one field. 就好像我有一个由一个字段映射的目标实体。

So far im using the entity repository and DI to load the associated Entities, but i find that ugly knowing there is a JOIN Statement which i could use: 到目前为止我使用实体存储库和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;
}

Twig 属性功能是您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM