Symfony 2 / Doctrine:如何降低查询的数量而不会损失ORM的好处? [英] Symfony 2/Doctrine: How to lower the num of queries without losing the benefit of ORM?

查看:98
本文介绍了Symfony 2 / Doctrine:如何降低查询的数量而不会损失ORM的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Symfony 2.7 Doctrine 。我的控制器动作通常如下所示:

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 %}

这导致许多SELECT查询,我想避免。到目前为止,我所知道的唯一解决方案是在存储库中收集所有需要的数据,并将其分配给操作,而不是在模板中抓取。

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.

我希望像在twig-snippet中看到一样。有没有任何可以检测我的案例的智能高速缓存选项,并自动优化查询?

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?

提前感谢!

推荐答案

正如其他人所说,您应该在存储库中获取组Entities。您可以使用这样的东西:

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

这篇关于Symfony 2 / Doctrine:如何降低查询的数量而不会损失ORM的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆