简体   繁体   English

使用Yii中的CActiveRecord计算相关模型中的列总和

[英]Calculate the sum of a column in related models using CActiveRecord in Yii

I have 2 tables: user(id,email,...) and task(id,uid,COMPLAINTS,..) 我有2个表:user(id,email,...)和task(id,uid,COMPLAINTS,..)

The relation is 关系是

'tasks' => array(self::HAS_MANY, 'Task', 'uid'),

I am displaying all the users in a grid view and want to add a column that shows the sum of the complaints column for tasks belonging to the user. 我正在网格视图中显示所有用户,并希望添加一列,以显示属于该用户的任务的投诉列的总和。 I was able to achieve this with this STAT relation in the User model: 我可以通过User模型中的STAT关系实现此目的:

'complaints'=>array(self::STAT, 'Task', 'uid', 'select'=>'SUM(complaints)', 'defaultValue'=>'0'),

However, this will create a lot of queries to the database when displaying in grid view. 但是,当在网格视图中显示时,这将对数据库创建很多查询。 But it can be done in a single query: 但这可以在单个查询中完成:

select user.*, sum(task.complaints) 
from user 
left join task 
on user.id=task.uid 
group by user.id

so I came up with this: 所以我想出了这个:

In the action method of the controller:
$criteria = new CDbCriteria;
$criteria->with = array('tasks'=>array('select'=>'sum(complaints) AS compl'));
$criteria->group = 't.id';

I can see this generates the right query when looking at the logs, however I'm not able to access the value for the sum. 我可以看到在查看日志时这会生成正确的查询,但是我无法访问总和的值。 Is this the right way of doing it? 这是正确的做法吗? If it is, then how can I access this new column? 如果是,那么我如何访问此新列?

then how can I access this new column? 那我该如何访问这个新列呢?

In GridView you just add this column among others: 在GridView中,您只需要添加此列:

$this->widget('zii.widgets.grid.CGridView', array(  
    'dataProvider'=>$dataProvider,  
    'columns'=>array(
        'id',
        'group',
        'tasks',
 ...

Update 更新资料

As Ali said previously, you need to define this property in model. 如Ali先前所述,您需要在模型中定义此属性。

class User {
  public $complain;
  ...
}

Then you assign it with values thru sql: 然后通过sql为其分配值:

$sql->db->createCommand('SELECT SUM(complaints) AS compl, id FROM <table_name>.t GROUP BY t.user_id');
$dataReader=$sql->queryAll(); 

this suppose to return the array of values groupped by user (user_id). 假定返回按用户(user_id)分组的值的数组。 See docs . 参见docs

Now you do next step to join them into models: 现在,您执行下一步以将它们加入模型:

$models=User::model()->findAll();
foreach($dataReader as $row)
{  
   $models[$row['id']]->complain=$row['compl'];
}
//the resulting $models you leverage for displaying in GridView.

Or you add these data $row['compl'] into ArrayDataProvider to join them with original model data for displaying in grid as well. 或者,您可以将这些数据$row['compl']ArrayDataProvider中,以将它们与原始模型数据结合起来,也可以在网格中显示。

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

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