[英]Allow ManyToMany Duplications on Symfony 5 (Doctrine)
我有一個問題,這是一個學校項目,我需要使用 Symfony 5 & Doctrine & ZE4728F444B24839E3F80ADF3829BCBA 允許我的應用程序上的兩個實體之間存在相同關系的重復
我在訂單和產品之間基本上有一個多對多關系,我不想為數量添加字段,所以我希望在我的 order_product 表上計算相同關系 id_order 和 id_product 的出現次數,但我可以'在訂單和產品之間保持不止一種相同的關系。
我搜索並主要看到人們試圖避免相同關系的重復,我正在尋找完全相反的情況。
謝謝
當在關系的至少一側使用與Many
的關系時,您會在另一側獲得Collection
。 在集合上,您可以調用count()
方法。
因此,如果您需要計算Order
中Products
的數量,您的Order
實體可以如下所示:
/** @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:還要注意字Order
是 PostgreSQL 中的保留字。 您需要以不同的方式命名您的Order
實體或正確轉義命名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.