Symfony 2/Doctrine: How to lower the num of queries without losing the benefit of ORM?(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 查询,我想避免这种情况.到目前为止,我知道的唯一解决方案是在 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 优势的情况下降低查询数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony 2/Doctrine:如何在不失去 ORM 优势的情况下降低查询数量?


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01