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(

	...

	'columns'=>array(

		'username',

		array(

			'name'=>'itemcount',

			'header'=>'Items',

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

		),

	),

	...

));

I tried adding a CSort to the CActiveDataProvider like so:


$sort = new CSort();

$sort->attributes = array(

	'*',

	'itemcount' => array(

		'asc'=>'<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' /> ASC',

		'desc'=>'<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' /> DESC',

	),

);

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

	'pagination'=>array(

		'pageSize'=>25,

	),

	'sort'=>$sort,

));

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!

Thanks,

Stu

bump?

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?

Thanks!

There you go buddy: http://www.yiiframework.com/forum/index.php?/topic/8164-please-sorting-by-count/page__view__findpost__p__41469

Use a scope

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