好吧,我花了一段时间,但我终于弄清楚了。 ;)
首先,确保您仍然具有您在问题中提到的相同 STAT 关系。
然后,在为 CActiveDataProvider 构建 CDbCriteria 的 search() 方法中,执行如下操作:
public function search() {
$criteria=new CDbCriteria;
$criteria->select = 't.*, IFNULL( count(article.id), 0) as articleCount';
$criteria->join = 'LEFT JOIN article ON article.userid = t.id';
$criteria->group = 't.id';
// other $criteria->compare conditions
$sort = new CSort();
$sort->attributes = array(
'articleCount'=>array(
'asc'=>'articleCountASC',
'desc'=>'articleCountDESC',
),
'*', // add all of the other columns as sortable
);
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
'sort'=>$sort,
'pagination'=> array(
'pageSize'=>20,
),
));
}
然后,在输出 CGridView 的视图中,执行以下操作:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'columns'=>array(
'articleCount',
// other columns here
)
)); ?>
这是可行的,我测试了它(虽然我没有使用完全相同的名称,如“文章”,但基本思想应该可行:)我确实添加了一些额外的功能,因此它工作得更好(如 IFNULL 魔术),但大多数归功于这个 Yii 论坛帖子:
http://www.yiiframework.com/forum/index.php?/topic/7061-csort-and-selfstat-to-sort-by-count/ http://www.yiiframework.com/forum/index.php?/topic/7061-csort-and-selfstat-to-sort-by-count/
我希望这有帮助!不过,他们应该为此添加更好的支持,因此您不需要创建这些棘手的 SELECT 语句。似乎应该“正常工作”,我会在Yii 错误跟踪器 http://code.google.com/p/yii/issues/list.