Symfony 2/Doctrine:如何在不失去 ORM 优势的情况下降低查询数量?

2022-01-01 00:00:00 orm php symfony doctrine twig

我使用 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();
}

相关文章