在yii中排序CListView

mmo*_*nem 9 php yii

请考虑一下:

class User extends CActiveRecord
{
    ...
    public function relations()
    {
        return array(
            ...    
            'articleCount' => array(self::STAT, 'Article', 'userid'),
            ...    
            );
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,我需要创建一个$dataProvider = new CActiveDataProvider(...)to to to a CListViewwidget我想要添加articleCount到该属性,sortableAttributes以便我可以根据用户是作者的文章数量对User记录进行排序.

什么是最方便的方法?还有什么其他选择?

tha*_*smt 21

好吧,我花了一段时间,但我终于明白了.;)

首先,请确保您在问题中仍然具有相同的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,
    ),
  ));
}
Run Code Online (Sandbox Code Playgroud)

然后,在您输出CGridView的视图中,执行以下操作:

<?php $this->widget('zii.widgets.grid.CGridView', array(
  'dataProvider'=>$model->search(),
  'columns'=>array(
    'articleCount',
    // other columns here
  )
)); ?>
Run Code Online (Sandbox Code Playgroud)

这工作,我测试它(虽然我没有使用完全相同的名称,如'文章',但基本的想法应该工作:)我确实添加了一些奖金功能,所以它更好(如IFNULL魔术)但大多数归功于Yii论坛帖子:http://www.yiiframework.com/forum/index.php?/topic/7061-cscs-and -selfstat-to-sort-by-count
/

我希望这有帮助!他们应该为此添加更好的支持,因此您不需要制作这些棘手的SELECT语句.看起来像应该"正常工作"的东西,我会在Yii bug跟踪器中提交"增强"请求.