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[]
* @ORMManyToMany(targetEntity="Species")
* @ORMJoinTable(name="product_species",
* joinColumns={@ORMJoinColumn(name="productId", referencedColumnName="id")},
* inverseJoinColumns={@ORMJoinColumn(name="speciesId", referencedColumnName="id")}
* )
* @ORMOrderBy({"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[]
*
* @ORMOneToMany(targetEntity="ProductIngredient", mappedBy="product")
* @ORMJoinColumn(name="productId", referencedColumnName="id")
*/
private $ingredients;
Now my ProductIngredient Entity Looks like this
/**
* @var IngredientType
* @ORMManyToOne(targetEntity="IngredientType", fetch="EAGER")
* @ORMJoinColumn(name="ingredientTypeId", referencedColumnName="id")
*/
private $ingredientType;
/**
* @var Ingredient
*
* @ORMManyToOne(targetEntity="Ingredient", inversedBy="products", fetch="EAGER")
* @ORMJoinColumns({
* @ORMJoinColumn(name="ingredientId", referencedColumnName="id")
* })
*/
private $ingredient;
/**
* @var Product
*
* @ORMManyToOne(targetEntity="Product", inversedBy="ingredients")
* @ORMJoinColumns({
* @ORMJoinColumn(name="productId", referencedColumnName="id")
* })
*/
private $product;
So in my product class for species I use the @ORMOrderBy 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());
See Question&Answers more detail:
os