0

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 Answers 2

1

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

$query = $this->createQueryBuilder('f, s')
// ...
Sign up to request clarification or add additional context in comments.

1 Comment

No, it is not working. Twig executes the sql request again. I think addSelect is the only way..
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.