symfony - 教义查询仅获得许多相关的“第一个”(执行连接和选择以避免 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”并指定排序?
解决方案
如果你想在 twig 中获取第一个报告,你只需要使用first
Collection 类的方法:
{% 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;
推荐阅读
- typescript - 我无法在 typescript react-native 中为“资产”设置模块解析器?
- reactjs - 如何在 setFieldValue 中使用 formik fieldarray 索引名称
- python - Tensorflow 输入维度不匹配问题
- python - 如何从 Heroku 应用程序下载最新更改的源代码和文件?
- vue.js - 错误 SSR _vm.formInstance.getFormData 不是函数
- php - Laravel Sail 不会在 Ubuntu 20.04 上构建 - groupadd:无效的组 ID 'sail'
- python - 如何使用正则表达式获取使用 boto3 的 s3 对象列表?
- javascript - HTML 中的 HTTP 安全标头
- c++ - 防止在静态库中隐式实例化 std::string/std::wstring
- javascript - 更改 sidenav 视图