Symfony 2/Doctrine:如何在不失去 ORM 优势的情况下降低查询数量? [英] Symfony 2/Doctrine: How to lower the num of queries without losing the benefit of ORM?

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

问题描述

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

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 查询,我想避免这种情况.到目前为止,我知道的唯一解决方案是在 repository 中收集所有需要的数据并在 action 中分配它,而不是在模板中爬行.

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?

提前致谢!

推荐答案

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

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天全站免登陆