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

标签 php symfony orm doctrine twig

我正在使用 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/

相关文章:

php - MVC现在是编写PHP的唯一方式吗?

php - 将 PHP 中的嵌套(多维)数组更改为 key => value 对

php - 私有(private)服务和 Symfony 4

java - JPA:数据库生成的列

orm - 如何在PetaPoco中使用SQL WHERE IN构造?

python - 使用 ID 列表进行过滤时,如何从 Django 查询中获取有限的结果?

php - 如果一个 url 是 404,curl_multi_exec 将停止,我该如何更改它?

php - 无法在 AMPPS 上启动 phpmyadmin

mysql - ORDER BY Count(p.id) 可能吗?

postgresql - 在自定义模式而不是公共(public)模式中配置doctrine_migration_versions表