sorting CGriwView on a SELF:STAT relation

Hi all,

I was wondering how I go about sorting a CGridView on a sum relation defined in the model?

Basically I have a table for users and a table for items. A user can have as many ‘items’ as they like, so my users model defines the number of items they have 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(

		'itemcount'=>array(self::STAT, 'Item', 'user_id'),



So I can call $model->itemcount and it’ll tell me how many items the user loaded into $model has. In my view I now have a table listing all my users, and I want to sort by this value:

$this->widget('zii.widgets.grid.CGridView', array(







			'value'=> '$data->itemcount',





I tried adding a CSort to the CActiveDataProvider like so:

$sort = new CSort();

$sort->attributes = array(


	'itemcount' => array(

		'asc'=>'<img src='' class='bbc_emoticon' alt='???' /> ASC',

		'desc'=>'<img src='' class='bbc_emoticon' alt='???' /> DESC',



$users=new CActiveDataProvider('User', array(






This allows the ‘itemcount’ colum to be clickable for sorting, but I can’t work out what I put in the CSort to allow it to actually work?

Any help would be greatly appreciated!




It seems to me that CSort isn’t the way to acheive this, does anyone know of, or can think of, a better way to do this?


There you go buddy:

Use a scope

Muchos gracias Antonio, I shall give that a go :)