CSort and self::STAT to sort by Count

I have been searching the forums and just can’t find a solution to this.

I am trying to sort a Gallery by the number of images in it. I have a Gallery table and Images table.

// Gallery model

public function relations()


  return array(

  'user' => array(self::BELONGS_TO, 'User', 'owner_id'),

  'images' => array(self::HAS_MANY, 'GallImg', 'gid'),

  'imgCount' => array(self::STAT, 'GallImg', 'gid'),



and in the controller I do

$crit = new CDbCriteria(array("with" => "imgCount"));

$pages = new CPagination(Gallery::model()->count($crit));

$pages->route = "gall/index";

$pages->pageSize = SAGD::STANDARD_LIST_SIZE;



$sort = new CSort('Gallery');

$sort->multiSort = false;

$sort->attributes = array('imgCount' => 'imgCount',);

$sort->defaultOrder = 'imgCount ASC';


$galls = Gallery::model()->findAll($crit);

which fails with error …

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'imgCount' in 'order clause'

I have a simmilar problem. I want to sort a CList by statistical queries. (How) did you solve this problem?

I solved it like that:

		$sort = new CSort('Thing');

		$sort->attributes =array(

			'points' => array(

				'asc'=>'numberOfPoints ASC',

				'desc'=>'numberOfPoints DESC',




		$dataProvider = new CActiveDataProvider('Thing', array(


				'select' => 't.*, COUNT(point.id) AS numberOfPoints',

				'join' => 'LEFT JOIN points_table point ON point.thing_id = t.id',

				'condition' => 'published_at IS NOT NULL',

				'group' => 't.id',



			'pagination'=>array('pageSize' => 3,)


and in the view:

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







Thanks a lot. Its very helpful for me as I am implementing this first time. :)

The Sorting works for me. But the filter does not work. Any solution please…