sdespont
sdespont

Reputation: 14025

Symfony2 : Display fetch join result in twig

I simply want to list all entities in a view from a table (building) which needs a join to display some details (building management). I want to use Doctrine fetch join option to avoid extra queries because every buildings must display its data from its building management.

Below is a basic controller example. My problem is that it is mandatory to include bm in the select in order to use fetch and not regular join. Therefore, the $entities variable contains b and bm entities and the loop in Twig is only waiting for b entities. How can I solve that?

public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    // This way is working, but extra queries are generated when I need to access the BuildingManagement data from Building entity
    //$entities = $em->getRepository('TrilogisPropertyBundle:Building')->findAll();

    $entities = $em->createQuery(
            'SELECT b, bm
             FROM MyBundle:Building b
             JOIN MyBundle:BuildingManagement bm WITH bm.building = b.id
             ORDER BY b.id')                                   
            ->getResult();

    return $this->render('MyBundle:Test:index.html.twig', array(
        'entities' => $entities,
    ));
}

And in TWIG

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Building Management</th>
        </tr>
    </thead>
    <tbody>
    {% for entity in entities %}
        <tr>
            <td>{{ entity.id }}</td>     
            <td>{{ entity.buildingManagement.id}}</td> <-- will crash because the entity must be a building and not a buildingManagement                                            
        </tr>
    {% endfor %}
    </tbody>
</table>

Upvotes: 1

Views: 859

Answers (1)

Jovan Perovic
Jovan Perovic

Reputation: 20201

If what you said about having relations between those two in comment holds true then you're probably doing JOIN the wrong way:

Query should probably be:

$entities = $em->createQuery(
            'SELECT b, bm
             FROM MyBundle:Building b
             JOIN b.buildingManagement bm
             ORDER BY b.id')                                   
            ->getResult();

Some things to note:

  • You will need a buildingManagement member in your Building entity in order for this to work.
  • buildingManagement should be, from the look of it, annotated with @ManyToOne. Could be @ManyToMany but that depends on app's logic.
  • Optionally, buildingManagement should be marked as inversed. We could help you determine that if you update your question with entities (both).

Upvotes: 2

Related Questions