Home > Back-end >  Sort multiple different entities by common attribute
Sort multiple different entities by common attribute

Time:12-13

Using Symfony 5.4.17. New to Symfony.

I have three similar Entity types and want to return an array called Food that I can loop over in a twig template like so:

    {% 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 %}

Here are is the code in the controller. Note that I get each of the food type objects that are related to the current user, and just for now put them in an array.

$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);

How can I store these three entity types sorted by Date into a renderable format? The idea is to have one loopable array that is already sorted by Date that contains any of the three types.

CodePudding user response:

With the help of @Cerad, I made an answer:

Sorting function in the Controller:

function date_sort($objA,$objB){
    if($objA->getDate() == $objB->getDate()) return 0;
    return ($objA->getDate() < $objB->getDate()) ? -1:1;
}

Controller view:

$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"));
  • Related