Yii2 activeRecord来自多个连接表的多个总和

时间:2017-09-11 07:00:36

标签: mysql activerecord yii2

当我加入多个表时,ActiveRecord查询构建器是否可以执行多个总和?

查询如下所示:

        $po = PurchaseOrder::find() //TODO groupby with multiple sums possible?
            ->select([
                'po.*',
                'sum(pi.invoice_units) as invoicedUnits',
                'sum(ar.received_units) as receivedArticles'
            ])
            ->from('purchase_order po')
            ->joinWith('invoice')
            ->joinWith('articlesReceived')
            ->where(['po.id' => 3960])
            ->groupBy(['po.id'])
            ->one();

我正在考虑的结果是:

sum(pi.invoice_units) = 234 + 2 = 236;
sum(ar.received_units) = 10 + 6 = 16;

但是我得到了这个:236*2 = 472; 16*2 = 32;

这样可以做多个总和吗?在普通的sql中,你会加入,然后在连接中加一个和,但是如何在activeRecord中做呢?

这是返回正确总和的正确查询:

SELECT po.*, ars.receivedArticles, pis.invoicedUnits FROM purchase_order po
    LEFT JOIN (SELECT ar.purchase_order_id, SUM(ar.received_units) as receivedArticles FROM purchase_articles_received ar GROUP BY ar.purchase_order_id) ars ON po.id = ars.purchase_order_id
    LEFT JOIN (SELECT pi.order_id, SUM(pi.invoice_units) as invoicedUnits FROM purchase_invoice pi GROUP BY pi.order_id) pis ON po.id = pis.order_id
    WHERE po.id = 3960 GROUP BY po.id;

0 个答案:

没有答案