檢索實(shí)體集合的最佳做法是什么DISTINCT COUNT?在此示例實(shí)體 ( Customer) 中,我oneToMany與 有關(guān)系Orders。我想計(jì)算客戶訂購了多少銷售額和產(chǎn)品:> 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()作品非常適合檢索產(chǎn)品數(shù)量,據(jù)說是“良好做法”,因?yàn)樗粫?huì)在完全加載集合時(shí)訪問數(shù)據(jù)庫:https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/tutorials/extra-lazy-associations.html如果您將關(guān)聯(lián)標(biāo)記為額外惰性,則可以在不觸發(fā)集合的完整加載的情況下調(diào)用集合的以下方法Collection#count()但是,在此示例中,aCustomer可以有多個(gè)產(chǎn)品用于銷售 - 其中salesRef是非唯一的。DISTINCT COUNT檢索的最佳方法是什么salesRef?
1 回答

喵喵時(shí)光機(jī)
TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
我認(rèn)為這應(yīng)該做到,并且是一種更便攜的方式。我沒有測(cè)試它。
? ? $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 關(guān)注
- 218 瀏覽
添加回答
舉報(bào)
0/150
提交
取消