Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

symfony - 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[]
 * @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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

/**
 * ...
 * @ORMOrderBy({"some_attribute" = "ASC", "another_attribute" = "DESC"})
 */
private $ingredients;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...