gpt4 book ai didi

php - Symfony 2/Doctrine : How to lower the num of queries without losing the benefit of ORM?

转载 作者:可可西里 更新时间:2023-11-01 00:59:26 25 4
gpt4 key购买 nike

我正在使用 Symfony 2.7Doctrine。我的 Controller 操作通常如下所示:

# my/namespace/Controller/ItemsController.php -> listAction()

$items = $this->get('repository.items')->findAll();
return $this->render('itemsList.html.twig', array('items' => $items));

在我的模板中,我喜欢迭代关联的实体:

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

我想保持在 twig-snippet 中看到的那样。是否有任何智能缓存选项可以检测像我这样的案例并自动优化查询?

提前致谢!

最佳答案

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

//inside the repository
public function findAllFetchGroups(){

return $this->createQueryBuilder('a')
->addSelect('gs')->join('a.groups', 'gs')
->getQuery()->getResult();
}

关于php - Symfony 2/Doctrine : How to lower the num of queries without losing the benefit of ORM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31660124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com