Home > front end >  What is the syntax for OrderBy in an entity using PHP 8 attributes
What is the syntax for OrderBy in an entity using PHP 8 attributes

Time:09-29

According to Doctrine documentation, one can order a field in an entity with @OrderBy({"name" = "ASC"}). With PHP 8 attributes, a field definition may look like this:

    #[ORM\Column(length: 25)]
    private ?string $food_name;

However, adding a sort like this: #[ORM\OrderBy({"food_name" = "ASC"})] is not acceptable syntax. Nor is #[ORM\OrderBy("food_name" = "ASC")].

Acceptable syntax such as #[ORM\OrderBy('food_name = ASC')] results in

Doctrine\ORM\Mapping\OrderBy::__construct(): Argument #1 ($value) must be of type array, string given

For this use case, Food is a collection field in a ManyToMany relationship with Meal. I'm trying to accomplish a sorted field so that a template that uses {% for food in meal.foods %} will render a pre-sorted food name list.

A) Can this be accomplished in the Food entity? or B) Should this be done in the Meal entity? or C) Is a presorted field not possible?

If presorted is possible, what is the correct syntax?

CodePudding user response:

Add the attribute on Meal.foods:

#[ORM\OrderBy(["food_name" => "ASC"])]
private $foods;

See also the documentation here: https://www.doctrine-project.org/projects/doctrine-orm/en/2.13/reference/attributes-reference.html#attrref_orderby

  • Related