douxi8119 2015-07-09 14:47
浏览 18

too long

In my Yii project, I have Order, Product, and OrderProduct models, interrelated. In order to get statistics on products sold within a certain period of time, I added the following relation in Product model: I have the following relation in Yii project:

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

Overall data is returned correctly. However, when I am trying to get data for orders within specific period of time - I get same numbers as the totals (sold over all the time).

I tried making the same thing in pure MySQL - this is the query that describes my needs:

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

But I don't know how to express it in a Yii way... Please help me.

PS. Tried adding condition in the relation, as follows:

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

Receive an error as the condition is on a related table, not product.

  • 写回答

1条回答 默认 最新

  • drsxzut183207938 2015-07-10 07:12
    关注

    As with is not defined in CStatRelation you have to provide condition through with statement as

    your relations in product model as

    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)'),
            );
        }
    

    and your condition 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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了