Alan
Alan

Reputation: 135

How to to an orderby on a ManyToMany relation field

i got an entity called "Recipes" that has a relation with another entity called "Ingredients".

/**
 * @ORM\ManyToMany(targetEntity=Ingredients::class, inversedBy="recettes")
 */
private $ingredient;

What i need is to list all ingredients via my form builder, and it works well :

->add('ingredient', EntityType::class, [
            // looks for choices from this entity
            'class' => Ingredients::class,
            'choice_label' => 'nom',
            // used to render a select box, check boxes or radios
            'multiple' => true,
            'expanded' => true,
            'label' => 'Ingrédients de la recette'
        ])

But i need to list them ordered by their name, so i've tried to add this line on my "Recipes ingredient field" :

* @OrderBy({"nom" = "ASC"})

But ingredients remains not ordered by their name.

Am i missing something ? :)

Upvotes: 0

Views: 82

Answers (1)

Giray Kefelioglu
Giray Kefelioglu

Reputation: 213

/**
 * ...
 * @ORM\OrderBy({"nom" = "ASC"})
 */
private $recettes;

or

->add('ingredient', EntityType::class, [
            // looks for choices from this entity
            'class' => Ingredients::class,
            'choice_label' => 'nom',
            // used to render a select box, check boxes or radios
            'multiple' => true,
            'expanded' => true,
            'label' => 'Ingrédients de la recette',
            'query_builder' => function (EntityRepository $er) {
                  return $er->createQueryBuilder('u')->orderBy('u.nom', 'ASC');
             },
        ])

Upvotes: 1

Related Questions