簡體   English   中英

Yii:STAT與條件的關系

[英]Yii: STAT relationship with condition

在我的Yii項目中,我具有相互關聯的OrderProductOrderProduct模型。 為了獲得一定時期內銷售產品的統計信息,我在產品模型中添加了以下關系:在Yii項目中,我具有以下關系:

...
'orderProductsCount' => array(self::STAT, 'OrderProduct', 'product_id', 'select' => 'SUM(quantity)'),
'orderProductsAmount' => array(self::STAT, 'OrderProduct', 'product_id', 'select' => 'SUM(total)'),
...

總體數據正確返回。 但是,當我嘗試獲取特定時間段內的訂單數據時-得到的數字與總數相同(一直銷售)。

我試圖在純MySQL中做同樣的事情-這是描述我的需求的查詢:

SELECT product.id,  `order`.added, COUNT( order_product.product_id ) , SUM( order_product.total ) 
FROM product
LEFT JOIN order_product ON order_product.product_id = product.id
LEFT JOIN  `order` ON  `order`.id = order_product.order_id
WHERE  `order`.added >  "2015-01-10"
GROUP BY product.id

但是我不知道如何用Yii方式表達它...請幫助我。

PS。 嘗試在關系中添加條件,如下所示:

'orderProductsAmount' => array(self::STAT, 'OrderProduct', 'product_id', 'select' => 'SUM(total)', 'condition' => 'orders.added < "2015-01-10"'),

由於條件在相關表而不是product上,因此會收到錯誤消息。

作為with不定義CStatRelation你必須通過with語句,以提供條件

您與產品模型之間的關系

public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'order' => array(self::MANY_MANY, 'Order', OrderProduct::model()->tableName().'(product_id,order_id)'),
            'amount'=>array(self::STAT, 'OrderProduct', 'product_id','select' => 'sum(total)'),
            'total'=>array(self::STAT, 'OrderProduct', 'product_id','select' => 'sum(product_id)'),
        );
    }

和您的條件findAll()

$model= Product::model()->with(array(
            'order' => array(
                'alias' => 'o',
                'condition' => 'o.added > :date',
                'params' => array(':date' => '2015-06-01')
            ),
            'amount' => array(),
            'total' => array()
        ))->findAll();

CVarDumper::dump($model,10,true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM