Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to OrderBy on OneToMany/ManyToOne

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 are relevant to each product.

I have mapping set up like this

Class product { /**  * @var Species[]  * @ORM\ManyToMany(targetEntity="Species")  * @ORM\JoinTable(name="product_species",  *      joinColumns={@ORM\JoinColumn(name="productId", referencedColumnName="id")},  *      inverseJoinColumns={@ORM\JoinColumn(name="speciesId", referencedColumnName="id")}  *      )  * @ORM\OrderBy({"name" = "asc"})  */ private $species; 

This works great for a manytomany/manyto one.

The problem is in my product_ingredients table I needed to add an additional field, meaning need to switch from ManyToMany to a OneToMany/ManyToOne So like this

/**      * @var ProductIngredient[]      *      * @ORM\OneToMany(targetEntity="ProductIngredient", mappedBy="product")      * @ORM\JoinColumn(name="productId", referencedColumnName="id")      */     private $ingredients; 

Now my ProductIngredient Entity Looks like this

 /**      * @var IngredientType      * @ORM\ManyToOne(targetEntity="IngredientType", fetch="EAGER")      * @ORM\JoinColumn(name="ingredientTypeId", referencedColumnName="id")      */     private $ingredientType;       /**      * @var Ingredient      *      * @ORM\ManyToOne(targetEntity="Ingredient", inversedBy="products", fetch="EAGER")      * @ORM\JoinColumns({      *   @ORM\JoinColumn(name="ingredientId", referencedColumnName="id")      * })      */     private $ingredient;      /**      * @var Product      *      * @ORM\ManyToOne(targetEntity="Product", inversedBy="ingredients")      * @ORM\JoinColumns({      *   @ORM\JoinColumn(name="productId", referencedColumnName="id")      * })      */     private $product; 

So in my product class for species I use the @ORM\OrderBy so that species is already ordered.. Is there a way I can somehow also do this for my ingredients field?

Or am I doing my logic wrong and these shouldn't even be fields on the product class and should just be looking up by the repository instead?

I was wanting it to be easy so I could loop through my objects like $product->getIngredients() instead of doing

$ingredients = $this->getDoctrine()->getRepository('ProductIngredient')->findByProduct($product->getId()); 
like image 508
Kris Avatar asked Sep 18 '12 14:09

Kris


1 Answers

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

/**  * ...  * @ORM\OrderBy({"some_attribute" = "ASC", "another_attribute" = "DESC"})  */ private $ingredients; 
like image 106
Andreas Linden Avatar answered Sep 19 '22 13:09

Andreas Linden