使用:
先在action里面生成分页对象,然后在前台的LinkPager中使用。
那如果要设置每页的大小或者再加排序怎么办?这个我已经对这个功能进行了封装
其中$config参数有:
先在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);
}
扫码二维码 获取免费视频学习资料

- 本文固定链接: http://phpxs.com/post/4917/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料
查 看2022高级编程视频教程免费获取