首页 > 解决方案 > 教义查询仅获得许多相关的“第一个”(执行连接和选择以避免 N+1)

问题描述

在这种情况下,我有 3 个相关实体 profile--OneToMany--> annualReports--ManyToOne-->photo

在一个循环中,对于一张桌子,我正在检查树枝中是否存在这样的照片

{% set is_photo = profile.annualReports.toArray()[0].photo.id is defined %}

所以,一个profile可以有很多annualReports——这种特殊情况我只想要第一个“报告”。

问题是我该怎么做QueryBuilder?即加入“first Report”(“first”可以基于最小id或者createdAt日期)

更新:我想问题是如何“限制 1”并指定排序?

标签: symfonydoctrine

解决方案


如果你想在 twig 中获取第一个报告,你只需要使用firstCollection 类的方法:

{% if profile.annualReports IS NOT EMPTY %}
   {% set report = profile.annualReports.first %}
{% endif%}

要管理订单,您必须使用教义注释'@OrderBy': https ://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#orderby


/**
 * @ManyToMany(targetEntity="Group")
 * @OrderBy({"name" = "ASC"})
 */
private $groups;


推荐阅读