meteor
meteor

Reputation: 658

Additional database requests when accessing object relates in twig template

When i write something like this:

controller:

public function listAction() {
    $actions = $this->getDoctrine()->getRepository('AcmeDemoBundle:Action')->findAll();

    return $this->render('AcmeDemoBundle:Admin:action/list.html.twig', 
            array('actions' => $actions));    
}

twig template:

        {% for action in actions %}
          ..........
            {% for descr in action.term.description %}
                <dd class="l-margin">{{ descr.text }}</dd>
            {% endfor %}

each time i'm accessing term, description, debug toolbar shows me that there makes request to database, to fetch each term or another relation. When i'm accessing them in controller there aren't this db requests.

when i write more detailed dql query like this:

    $qb->select('action, term, descr')
        ->from('AcmeDemoBundle:Action', 'action')
        ->join('action.term', 'term');
        ->join('term.description', 'descr');

all additional requests disappear. It must be so?

Upvotes: 0

Views: 185

Answers (2)

Javad
Javad

Reputation: 4397

It's what it is; means either in TWIG file or your controller if you call a related object from the result of a query which objects are not added to your select will fetch a DB query. e.g:

$actions = $this->getDoctrine()->getRepository('AcmeDemoBundle:Action')->findAll();
foreach ($actions as $action) {
   print $action->getTerm()->getDescription();
   ...
}

And same in twig for the same top query:

{% for action in actions %}
     <dd class="l-margin">{{ action.getTerm.getDescription }}</dd>

These top examples will fire a DB query because the related entities are not added to the select. Same selection with added related entities to your select query will reduce amount of executed DB queries but will lead to a select of a multiplied rows and columns for join(s) depends on type of join used in query e.g:

$result = $em->createQueryBuilder('A')
   ->addSelect('A.term')
   ->join('A.term', 'T')
   ->getQuery()
   ->getResult();

Now either in controller or in TWIG file if you call $action->getTerm()->getDescription() or {{ action.getTerm.getDescription }} it won't execute a separate DB query because it was added to your select when you built your query.

Upvotes: 1

dmnptr
dmnptr

Reputation: 4304

The reason you see all those queries in TWIG is that you are accessing them when requesting action.term. Doctrine adds those queries for you. When you use joins, they are requested all in one query. This is documented here - http://symfony.com/doc/current/book/doctrine.html#joining-related-records. Using joins is recommended to avoid extra queries.

Upvotes: 1

Related Questions