简体   繁体   English

Yii和ActiveRecord Group by Count

[英]Yii and ActiveRecord Group by Count

I'm relatively new to Yii and would like to experiment a little. 我对Yii比较陌生,想尝试一下。 I have looked around all over the internet and I have absolutely no idea how to approach this. 我在互联网上四处看看,我完全不知道如何处理这个问题。 I have mastered the basics of Yii but I think that this is quite advanced or I'm just being stupid. 我已经掌握了Yii的基础知识,但我认为这是非常先进的,或者我只是愚蠢。

I have a MYSQL table with a list of items bought. 我有一个MYSQL表,其中列出了所购买的商品。 This table has CUSTOMER_ID as the main field with each CUSTOMER_ID possibly having more than one ITEM's. 该表将CUSTOMER_ID作为主要字段,每个CUSTOMER_ID可能具有多个ITEM。 I would like to do a count BY TRANSACTION_ID and then assess as in line with the following logic: 我想通过TRANSACTION_ID进行计数,然后根据以下逻辑进行评估:

1) IF myCount = 1 then businessType = 'New'; 
2) If myCount = 2 then businessType = 'Repeat'; 
3) If myCount > 2 then businessType = '2+ Repeat'; 

I'm not sure where and how would be the best way to do this however? 我不知道在哪里以及如何做到这一点最好的方法呢? afterSave()?? afterSave()? Or in the controller? 还是在控制器中? I have to get the result of the query into a GROUPED CActiveDataProvider object as I feed this data into Highcharts. 我必须将查询结果导入GROUPED CActiveDataProvider对象,因为我将此数据提供给Highcharts。

My grouping needs to look as follows (From lowest level to highest) : 我的分组需要看如下(从最低级别到最高级别):

businessType->store->item->{Count(ITEM), SUM(Cost)}

I am unfortunately not able to add a variable to the table and would really like to achieve this without having to. 遗憾的是,我无法在表中添加变量,并且非常希望无需实现此目的。 Any help appreciated! 任何帮助赞赏!

to do this you will need to use CDbCriteria to group results in a CActiveDataProvider. 为此,您需要使用CDbCriteria将结果分组到CActiveDataProvider中。 See here http://www.yiiframework.com/doc/api/1.1/CDbCriteria#group-detail . 请参见http://www.yiiframework.com/doc/api/1.1/CDbCriteria#group-detail You'll need to implement it in your controller something like this; 你需要在你的控制器中实现这样的东西;

$criteria = new CDbCriteria;
$criteria->select = 'the columns to select, and maybe SUM()';
$criteria->group = 'columns to group by';
etc
etc

$dataProvider = new CActiveDataProvider('model name', $criteria);

Without knowing the exact implementation of your database I can only give a general example, but you should find something like this works for you. 在不知道数据库的确切实现的情况下,我只能给出一个通用的例子,但你应该找到适合自己的东西。 I'm not sure how to get the grouping your talking about as businessType->store->item->{Count(ITEM), SUM(Cost)} , as you haven't shown your database and model structure. 我不知道如何将你所说的分组称为businessType->store->item->{Count(ITEM), SUM(Cost)} ,因为你没有显示你的数据库和模型结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM