亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

學說區別計數

學說區別計數

PHP
泛舟湖上清波郎朗 2023-05-26 17:35:00
檢索實體集合的最佳做法是什么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();

查看完整回答
反對 回復 2023-05-26
  • 1 回答
  • 0 關注
  • 204 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號