yii2.0分页
分页有两种方法:
第一种:
控制器:
use yii\data\ActiveDataProvider; //引用 use yii\data\Pagination; //分页类 public function actionShow1() { $query=Login::find(); //Login是model名 $provider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 5, //每页条数 ], ]); return $this->render('index', [ 'model' => $query, 'dataProvider' => $provider ]); }
view层:index.php
<?php use yii\helpers\Html; use yii\grid\GridView; use yii\widgets\LinkPager; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = '展示'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="login-index"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('添加', ['index'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'pager'=>[ //'options'=>['class'=>'hidden']//关闭自带分页 'firstPageLabel'=>"首页", 'prevPageLabel'=>'上一页', 'nextPageLabel'=>'下一页', 'lastPageLabel'=>'尾页', ], 'columns' => [ //['class' => 'yii\grid\SerialColumn'], 'login_id', 'login_name', ['attribute'=>'addtime', 'format'=>['date','php:m-d h:i:s'], ], ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
效果为:
第二种方法:
控制器:
public function actionShow1() { $query=Login::find(); $pagination = new Pagination([ 'defaultPageSize' => 5,//每页显示条数 'totalCount' => $query->count(),//总条数 ]);//分页传参 $countries = $query->orderBy('login_id asc') ->offset($pagination->offset)//偏移量 ->limit($pagination->limit) ->all();//查询到的分页后的数据 return $this->render('index', [ 'countries' => $countries, 'pagination' => $pagination, ]); }
views层:
<?php use yii\helpers\Html; use yii\grid\GridView; use yii\widgets\LinkPager; //引用分页link /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = '展示'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="login-index"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('添加', ['index'], ['class' => 'btn btn-success']) ?> </p> <center> <table border="1" cellpadding ="5"> <tr> <td>编号</td> <td>名称</td> <td>添加时间</td> <td>操作</td> </tr> <?php foreach ($data as $key => $v): ?> <tr> <td><?= Html::encode($v['login_id'])?></td> <td><?= Html::encode(mb_substr($v['login_name'],0,3)."*")?></td> <td><?= Html::encode(date('Y-m-d H:i:s',$v['addtime']))?></td> <td><?= Html::a('查看', ['select','login_id'=>$v['login_id']], ['class' => 'btn btn-success']) ?> <?= Html::a('修改', ['update','login_id'=>$v['login_id'],'a'=>$v['login_id']], ['class' => 'btn btn-success']) ?></td> </tr> <?php endforeach; ?> </table> <?= LinkPager::widget([ 'pagination'=>$pagination, //'options'=>['class'=>'hidden']//关闭自带分页 'firstPageLabel'=>"首页", 'prevPageLabel'=>'上一页', 'nextPageLabel'=>'下一页', 'lastPageLabel'=>'尾页', ]) ?> </center> </div>
效果图:
以上就是两种分页方法。