檢索實體集合的最佳做法是什么DISTINCT COUNT?在此示例實體 ( Customer) 中,我oneToMany與 有關系Orders。我想計算客戶訂購了多少銷售額和產品:> select * from orders;+----------+----------+----------+| customer | sale_ref | prod_ref |+----------+----------+----------+| 1 | sale_1 | prod_1 || 1 | sale_1 | prod_2 || 1 | sale_2 | prod_1 || 1 | sale_3 | prod_3 |+----------+----------+----------+> select count(prod_ref) from order where customer = 1;+-----------------+| count(prod_ref) |+-----------------+| 4 |+-----------------+> select count(distinct(sale_ref)) from order where customer = 1;+-----------------+| count(prod_ref) |+-----------------+| 3 |+-----------------+這是代碼use Doctrine\ORM\Mapping as ORM;class Customer{ /** * @var \Doctrine\Common\Collections\Collection * @ORM\OneToMany(targetEntity="Orders", mappedBy="customer", cascade={"persist", "remove"}, fetch="EXTRA_LAZY") */ protected $orders; /** * @return \Doctrine\Common\Collections\Collection */ public function getOrders(): \Doctrine\Common\Collections\Collection { return $this->orders; } /** * @return int */ public function getOrdersProductCount(): int { return $this->orders->count(); }}class Orders{ /** * @var Customer $customer * @ORM\ManyToOne(targetEntity="Customer", inversedBy="orders") */ protected $customer; /** * Non-unique sales reference * @var string $salesRef * @ORM\Column(name="sales_ref", type="string") */ protected $salesRef;使用該Customer->getOrdersProductCount()作品非常適合檢索產品數量,據說是“良好做法”,因為它不會在完全加載集合時訪問數據庫:https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/tutorials/extra-lazy-associations.html如果您將關聯標記為額外惰性,則可以在不觸發集合的完整加載的情況下調用集合的以下方法Collection#count()但是,在此示例中,aCustomer可以有多個產品用于銷售 - 其中salesRef是非唯一的。DISTINCT COUNT檢索的最佳方法是什么salesRef?
1 回答

喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
我認為這應該做到,并且是一種更便攜的方式。我沒有測試它。
? ? $qb = $this->createQueryBuilder('o');
? ? return (int)$qb
? ? ? ? ->select($qb->expr()->countDistinct('o.salesRef'))
? ? ? ? ->where('o.customer = :customer')
? ? ? ? ->setParameter('o.customer', $customer)
? ? ? ? ->setMaxResults(1)
? ? ? ? ->getQuery()
? ? ? ? ->getSingleScalarResult();
- 1 回答
- 0 關注
- 204 瀏覽
添加回答
舉報
0/150
提交
取消