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 优势的情况下降低查询数量?


基础教程推荐
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01