Symfony 2/Doctrine:如何在不失去 ORM 优势的情况下减少查询数量?
Symfony 2/Doctrine: How to lower the num of queries without losing the benefit of ORM?
我正在使用 Symfony 2.7 和 Doctrine。我的控制器操作通常如下所示:
# 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-查询,我想避免这种情况。到目前为止,我知道的唯一 解决方案 是在 repository
中收集所有需要的数据并在 action
中分配它,而不是在模板中爬行。
我想保持在 twig-snippet 中看到的那样。是否有任何智能缓存选项可以检测像我这样的案例并自动优化查询?
提前致谢!
有两种方法可以实现您的目标。您可以 fetch="EAGER" 您的相关数据(但它总是加载可能不是必需的数据)或使用查询构建器加入相关集合,它将在一个查询中加载。但请记住,要保持代码干净——不要在存储库之外查询 :)
正如其他人所说,您应该在存储库中获取组实体。你可以使用这样的东西:
//inside the repository
public function findAllFetchGroups(){
return $this->createQueryBuilder('a')
->addSelect('gs')->join('a.groups', 'gs')
->getQuery()->getResult();
}
我正在使用 Symfony 2.7 和 Doctrine。我的控制器操作通常如下所示:
# 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-查询,我想避免这种情况。到目前为止,我知道的唯一 解决方案 是在 repository
中收集所有需要的数据并在 action
中分配它,而不是在模板中爬行。
我想保持在 twig-snippet 中看到的那样。是否有任何智能缓存选项可以检测像我这样的案例并自动优化查询?
提前致谢!
有两种方法可以实现您的目标。您可以 fetch="EAGER" 您的相关数据(但它总是加载可能不是必需的数据)或使用查询构建器加入相关集合,它将在一个查询中加载。但请记住,要保持代码干净——不要在存储库之外查询 :)
正如其他人所说,您应该在存储库中获取组实体。你可以使用这样的东西:
//inside the repository
public function findAllFetchGroups(){
return $this->createQueryBuilder('a')
->addSelect('gs')->join('a.groups', 'gs')
->getQuery()->getResult();
}