Symfony 2/Doctrine: How to lower the num of querie

2019-01-28 09:49发布

问题:

I'm using Symfony 2.7 with Doctrine. My controller actions often look like:

# my/namespace/Controller/ItemsController.php -> listAction()

$items = $this->get('repository.items')->findAll();
return $this->render('itemsList.html.twig', array('items' => $items));

In my templates I like to iterate associated Entities:

# my/namespace/Resources/views/itemsList.html.twig

{% for item in items %}
    Item: {{ item.name }} <br/>
    Groups: <br/>
    <ul>
    {% for group in item.groups %}
        <li>{{ group.name }}</li>
    {% endfor %}
    </ul>
{% endfor %}

This causes many SELECT-queries, which I'd like to avoid. The only solution I know so far is collecting all needed data in a repository and assigning it in the action, instead of crawling within the template.

I'd like to keep it that way as seen in the twig-snippet. Are there any smart caching options that might detect cases like mine and optimize the queries automatically?

Thanks in advance!

回答1:

As other's have said, you should fetch the group Entities inside your repository. You can use something like this:

//inside the repository
public function findAllFetchGroups(){

  return $this->createQueryBuilder('a')
    ->addSelect('gs')->join('a.groups', 'gs')
    ->getQuery()->getResult();
}


回答2:

There is two ways to accomplish your target. You can fetch="EAGER" your related data (but it loads always maybe not necessary data) or use query builder to join related collection, it will be loaded in one query. But remember, to keep code clean - no queries outside repositories :)