[英]Sorting CListView in yii
请考虑一下:
class User extends CActiveRecord
{
...
public function relations()
{
return array(
...
'articleCount' => array(self::STAT, 'Article', 'userid'),
...
);
}
...
}
现在,我需要创建一个$dataProvider = new CActiveDataProvider(...)
来提供我想要将articleCount
添加到属性sortableAttributes
的CListView
小部件,以便我可以根据用户是作者的文章数量对用户记录进行排序对于。
什么是最方便的方法? 还有什么其他选择?
好吧,我花了一段时间,但我终于明白了。 ;)
首先,请确保您仍然具有在问题中提到的相同的STAT关系。
然后,在您为searchctiveDataProvider构建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/
我希望这有帮助! 他们应该为此添加更好的支持,因此您不需要制作这些棘手的SELECT语句。 看起来像应该“正常工作”的东西,我会在Yii bug跟踪器中提交“增强”请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.