Yii Framework Forum: count() with group by - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

count() with group by

#1 User is offline   coriolan 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 26-November 14

Posted 06 May 2015 - 06:40 AM

Hi,

For a stats page, I needed to know how many users of each type I had.
There is a lot of discussion online on how to do this. This is the simplest I found, so I thought I'd share...

Model:
// Variable holding the count value - required !
public $user_count;
public function search($dateReadingRange=null)
{
	$criteria=new CDbCriteria;
	$criteria->compare('t.id',$this->id,true);
	$criteria->compare('usertype_id',$this->number);
	$criteria->compare('name',$this->name,true);
	(... more conditions ...)

	// Grouping
	$criteria->group = 'usertype_id';
	// Counting. The result of this will automagically be stored in $model->user_count
	$criteria->select = "count(t.id) as user_count";

	(...)


View
(... gridview definition ...)
'columns'=>array(
	array(
		'name' => 'user_count',
		'value' => '$data->submeter_count',
	),
(...more columns...)

1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users