symfony 按公共属性对多个不同实体进行排序

lokaqttq  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(121)

使用Symfony 5.4.17。Symfony的新功能。
我有三个相似的Entity类型,我想返回一个名为Food的数组,我可以在一个twig模板中循环遍历它,如下所示:

{% 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排序的实体类型存储为可呈现的格式?我们的想法是创建一个已按Date排序的可循环数组,其中包含这三种类型中的任何一种。

gc0ot86w

gc0ot86w1#

在@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"));

相关问题