3

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!

Mr. B.
  • 8,041
  • 14
  • 67
  • 117
  • 3
    Have you tried eager loading i.e. `fetch="EAGER"` ? – FuzzyTree Jul 27 '15 at 18:07
  • 1
    Have you tried writing your own repository method, witch joins and selects the groups as well? – Maerlyn Jul 27 '15 at 20:00
  • 1
    @FuzzyTree `fetch="EAGER"` works for some cases, thanks! I'm trying to use it with caution and prefer my own repository method, supplemented by `fetch="EAGER"`. – Mr. B. Jul 29 '15 at 17:58

2 Answers2

3

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();
}
user2268997
  • 1,263
  • 2
  • 14
  • 35
1

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 :)