【问题标题】:Doctrine2: dynamic entity associations, many targetEntity mapped by one fieldDoctrine2:动态实体关联,一个字段映射多个targetEntity
【发布时间】:2012-03-28 22:59:38
【问题描述】:

我有一个名为 Event 的实体,它有

  • “关联实体”字段包含 Bundle 中另一个实体的类名
  • 该特定“关联实体”实体的字段“targetId”

我现在想以某种方式访问​​我的 Event-Entity 中的这个目标实体,但我现在知道该怎么做。我想使用类似

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

编辑:为了清楚起见,到目前为止我唯一感兴趣的是如何正确创建关系。在 ORM World 之外,您可能会为此使用 join 语句。就像我有许多目标实体被一个字段映射。

到目前为止,我使用实体存储库和 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;
}

【问题讨论】:

  • 您是否想让 Event.target 能够指向不同的目标类?如果是这样,那可能有点挑战。
  • 是的,这就是我想做的事!

标签: php symfony doctrine doctrine-orm


【解决方案1】:

Twig attribute function 是你需要的。

【讨论】:

  • 好的,但是我如何创建实体关系?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多