dd

Yii2.0实用功能技巧解密之——分页功能

十度 Yii2 2015年11月30日 收藏

Yii中的分页功能主要由yii\web: Linkable接口、yii\widgets: LinkPager类和yii\data: Pagination类三个组成。

  • yii\data: Pagination 主要功能是对分页中的参数进行设置,如当前页、每页大小、总页数,总记录数等。
  • yii\widgets: LinkPager 主要是根据yii\data: Pagination类所提供的参数生成前台页面的分页html代码。


使用:

先在action里面生成分页对象,然后在前台的LinkPager中使用。
后台controller中:

function actionIndex()
{
        $query = Article::find()->where(['status' => 1]);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $models = $query->offset($pages->offset)
          ->limit($pages->limit)
          ->all();
        return $this->render('index', [
           'models' => $models,
           'pages' => $pages,
        ]);
}


前台view中:

foreach ($models as $model) {
        // display $model here
}
// display pagination
echo LinkPager::widget([
        'pagination' => $pages,
]);


增强版

那如果要设置每页的大小或者再加排序怎么办?这个我已经对这个功能进行了封装
在基类控制器中添加:

public function getPagedRows($query,$config=[])
{
        $countQuery = clone $query;
        $pages=new Pagination(['totalCount' => $countQuery->count()]);
        if(isset($config['pageSize']))
        {
                $pages->setPageSize($config['pageSize'],true);
        }
        $rows = $query->offset($pages->offset)->limit($pages->limit);
        if(isset($config['order']))
        {
                $rows = $rows->orderBy($config['order']);
        }
        $rows = $rows->all();
        $rowsLable='rows';
        $pagesLable='pages';
        if(isset($config['rows']))
        {
                $rowsLable=$config['rows'];
        }
        if(isset($config['pages']))
        {
                $pagesLable=$config['pages'];
        }
        $ret=[];
        $ret[$rowsLable]=$rows;
        $ret[$pagesLable]=$pages;
        return $ret;
}

其中$config参数有:

  • pageSize:设置每页的大小
  • order:数据的排序
  • rows:返回的数组中数据对象的键名
  • pages:返回的数组中分页对象的键名


后台使用如下:

function actionIndex()
{
        $query = Article::find()->where(['status' => 1]);
        //因为前台的数据对象为models,所以设置rows名称为models
        $locals = $this->getPagedRows($query, ['order'=>'time desc', ‘pageSize’=>5, 'rows'=>'models']);
        return $this->render('index', $locals);
}
是不是简单多了,而且由于这个功能实现在基类里面,所有的控制器都可以直接拿来用。
dd