How to OrderBy on OneToMany/ManyToOne

后端 未结 4 627
粉色の甜心
粉色の甜心 2020-12-08 19:29

I have a Product class that has many fields on it for ManyToMany, such as ingredients, sizes, species, etc.. A total of about 14 different fields Not all of the fields are a

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 20:12

    Well I came up with a hackish way.. Since I really only care about the sort on output, I have made a basic twig extension

    use Doctrine\Common\Collections\Collection;
    
    public function sort(Collection $objects, $name, $property = null)
    {
        $values = $objects->getValues();
        usort($values, function ($a, $b) use ($name, $property) {
            $name = 'get' . $name;
            if ($property) {
                $property = 'get' . $property;
                return strcasecmp($a->$name()->$property(), $b->$name()->$property());
            } else {
                return strcasecmp($a->$name(), $b->$name());
            }
        });
        return $values;
    }
    

    I would like to avoid this hack though and still would like to know a real solution

提交回复
热议问题