Symfony 5.4.17:合并三类实体并按Date排序为可遍历数组
解决Symfony多实体合并排序问题
步骤1:合并三类实体数据
先将你已获取到的三类实体集合转成数组并合并。假设你已经通过Repository拿到了当前用户关联的三类数据:
// 已获取的三类实体数据(单类按Date升序排列) $menustatFoods = $this->getDoctrine()->getRepository(MenustatFood::class)->findBy(['user' => $currentUser], ['date' => 'ASC']); $usdaBrandedFoods = $this->getDoctrine()->getRepository(UsdaBrandedFood::class)->findBy(['user' => $currentUser], ['date' => 'ASC']); $usdaNonBrandedFoods = $this->getDoctrine()->getRepository(UsdaNonBrandedFood::class)->findBy(['user' => $currentUser], ['date' => 'ASC']); // 合并为一个数组 $allFoods = array_merge($menustatFoods, $usdaBrandedFoods, $usdaNonBrandedFoods);
步骤2:对合并后的数组按Date排序
用PHP的usort函数,依据实体的Date属性排序(需确保三类实体都有getDate()方法,返回DateTime对象):
// 按Date升序排序 usort($allFoods, function($a, $b) { // 处理Date为null的情况,避免报错 $dateA = $a->getDate() ?? new DateTime('1970-01-01'); $dateB = $b->getDate() ?? new DateTime('1970-01-01'); return $dateA->getTimestamp() - $dateB->getTimestamp(); }); // 若要降序,调换差值顺序即可: // return $dateB->getTimestamp() - $dateA->getTimestamp();
步骤3:传递给Twig模板并遍历
把排序后的数组传给模板,在Twig中直接循环遍历:
// 控制器中传递变量到模板 return $this->render('food/list.html.twig', [ 'foodArr' => $allFoods, ]);
Twig模板中的遍历代码:
{% for food in foodArr %} <div class="food-item"> <span>{{ food.date|date('Y-m-d H:i') }}</span> <span>{{ food.title }}</span> {# 替换为你的实体实际属性 #} </div> {% endfor %}
注意事项
- 确保三类实体都实现了
getDate()方法,返回类型一致(推荐DateTimeInterface); - 如果
Date字段允许为null,排序时要做兜底处理,避免致命错误; - 若数据量极大,内存排序可能影响性能,此时建议考虑Doctrine联合查询或数据库视图优化。
内容的提问来源于stack exchange,提问作者Steak
相关产品推荐
相关产品推荐

