使用 Symfony 5.4.17。 Symfony 新手。
我有三个相似的实体类型,想要返回一个名为
Food
的数组,我可以在树枝模板中循环它,如下所示:
{% for food in foodArr %}
<div class = 'border p-3 mb-3'>
<a href="/food/show/{{get_class(food)}}/{{food.id}}">View</a>
<p>Food Name: {{food.Description}}</p>
<p>Food Id: {{food.id}}</p>
<p>Date: {{food.Date|date('m-d-Y')}}</p>
<a href="/food/delete/{{get_class(food)}}/{{food.id}}">Delete?</a>
</div>
{% endfor %}
这是控制器中的代码。请注意,我获取了与当前用户相关的每个食物类型对象,并且暂时将它们放入数组中。
$menustatFoodRepo = $this->em->getRepository(MenustatFood::class);
$usdaBrandedFoodRepo = $this->em->getRepository(UsdaBrandedFood::class);
$usdaNonBrandedFoodRepo = $this->em->getRepository(UsdaNonBrandedFood::class);
$menustatFoods= $menustatFoodRepo->findBy(
['User' => $this->getUser()],
['Date' => 'ASC']
);
$usdaBrandedFoods = $usdaBrandedFoodRepo -> findBy(
['User' => $this->getUser()],
['Date' => 'ASC']
);
$usdaNonBrandedFoods = $usdaNonBrandedFoodRepo -> findBy(
['User' => $this->getUser()],
['Date' => 'ASC']
);
$foodArr = array();
// add all foods to array
array_push($foodArr,$menustatFoods,$usdaBrandedFoods,$usdaNonBrandedFoods);
如何将按
Date
排序的这三种实体类型存储为可渲染格式?这个想法是拥有一个已按日期排序的可循环数组,其中包含三种类型中的任何一种。
在@Cerad的帮助下,我做出了答案:
控制器中的排序功能:
function date_sort($objA,$objB){
if($objA->getDate() == $objB->getDate()) return 0;
return ($objA->getDate() < $objB->getDate()) ? -1:1;
}
控制器视图:
$menustatFoodRepo = $this->em->getRepository(MenustatFood::class);
$usdaBrandedFoodRepo = $this->em->getRepository(UsdaBrandedFood::class);
$usdaNonBrandedFoodRepo = $this->em->getRepository(UsdaNonBrandedFood::class);
$menustatFoods= $menustatFoodRepo->findBy(
['User' => $this->getUser()],
['Date' => 'ASC']
);
$usdaBrandedFoods = $usdaBrandedFoodRepo -> findBy(
['User' => $this->getUser()],
['Date' => 'ASC']
);
$usdaNonBrandedFoods = $usdaNonBrandedFoodRepo -> findBy(
['User' => $this->getUser()],
['Date' => 'ASC']
);
$foodArr = array_merge($menustatFoods,$usdaBrandedFoods,$usdaNonBrandedFoods);
// add all foods to array
usort($foodArr,array($this,"date_sort"));