[英]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.