0
votes

When using Twig with Doctrine on related entities, a new SQL request is launch every time I want to access a new related variable, like {{ flight.flightSteps[0].position}}

I read on another post here : Symfony2 and Doctrine2 - QueryBuilder with relational entities this:

When you do $p->getSection()->getName() from a Controller or p.section.name from a Twig template, without having stated the JOIN in the query (with default QueryBuilder), Doctrine requests missing informations of the relation at this time. That could be very heavy if you do that in a loop, like in a list display... So try to load what you need from relations at first request ;)

It ends with:

So try to load what you need from relations at first request ;)

So I am looking for a way to create a request directly with the QueryBuilder so that when I call a related variable in my Twig template the query is not executed one more time, but I don't find how to do it.

Here is what I did but that did not work:

$query = $this->createQueryBuilder('f')
                ->where('f.id = :id')
                ->setParameter('id', $id)
                ->leftJoin('f.flightSteps', 's')
                ->orderBy('s.sortPosition', 'ASC')
                ->getQuery();

return $query->getResult();

I still have a new SQL request executed when I call {{ flight.flightSteps[0].position }}

2

2 Answers

1
votes

I think you could also, add the s in the createQueryBuilder() too:

$query = $this->createQueryBuilder('f, s')
// ...
0
votes

After 2 days of research, I jut found the solution just after I posted it...

I need to add an addSelect like it:

$query = $this->createQueryBuilder('f')
            ->where('f.id = :id')
            ->setParameter('id', $id)
            ->leftJoin('f.flightSteps', 's')
            ->orderBy('s.sortPosition', 'ASC')
            ->addSelect('s')
            ->getQuery();

return $query->getResult();