简体   繁体   中英

Allow ManyToMany Duplications on Symfony 5 (Doctrine)

I have a problem, it's for a school project and I need to allow duplications of the same relation between two entities on my app using Symfony 5 & Doctrine & postgresql.

I have a basicly a ManyToMany relation between Order and Products, I don't want to add fields for quantity, so I'm looking to count the number of occurences of the a same relation id_order & id_product on my order_product table, but I can't persist more than one same relation between order & product.

I searched and mainly saw people tryng to avoid duplications of the same relation, i'm looking for the exact contrary.

Thx

When using relation with Many on at least one side of the relation, you get Collection on the opposite side. On the collection you can call count() method.

So if you need to calculate quantity of Products in your Order , your Order entity can look like this:

/** @Entity */
class Order
{
    ...

    /**
     * @ManyToMany(targetEntity="Product", inversedBy="orders")
     * @JoinTable(name="order_product")
     */
    private $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }

    public function countProducts(): int
    {
        return $this->products->count();
    }

    public function countProductsById(int $productId): int
    {
        return $this->products->filter(static function(Product $product) use ($productId) {
            return $product->getId() === $productId;
        })->count();
    }

    ...
}

PS: Also be aware that word Order is a reserved word in PostgreSQL. You need to either name your Order entity differently or escape the naming correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM