How to OrderBy on OneToMany/ManyToOne

后端 未结 4 585
粉色の甜心
粉色の甜心 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:06

    in the Product entity just also aadd the orderBy to the ingredients relation

    /**
     * ...
     * @ORM\OrderBy({"some_attribute" = "ASC", "another_attribute" = "DESC"})
     */
    private $ingredients;
    
    0 讨论(0)
  • 2020-12-08 20:10

    You should use 'query_builder' option in your Form: http://symfony.com/doc/master/reference/forms/types/entity.html#query-builder The value of the option can be something like this:

    function(EntityRepository $er) {
        return $er->createQueryBuilder('i')->orderBy('i.name');
    }
    

    Don't forget to add the "use" statement for EntityRepository

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-08 20:12

    If you use xml mapping, you could use

            <order-by>
                <order-by-field name="some_field" direction="ASC" />
            </order-by>
    

    inside your <one-to-many> tag.

    0 讨论(0)
提交回复
热议问题