Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Entity called Event which has

  • a field "associatedEntity" containing the class name of another Entity in the Bundle
  • a field "targetId" of that specific "associatedEntity" Entity

I would now like to access this target entity inside my Event-Entity somehow but im now sure how to do it. 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. 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:

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;
}
like image 689
worenga Avatar asked Nov 14 '22 08:11

worenga


1 Answers

Twig attribute function is what you need.

like image 82
Hubert Perron Avatar answered Nov 16 '22 04:11

Hubert Perron