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());
in the Product entity just also aadd the orderBy to the ingredients relation
/** * ... * @ORM\OrderBy({"some_attribute" = "ASC", "another_attribute" = "DESC"}) */ private $ingredients;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With