ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ### 一、使用LinkPager #### 1.模型方式 ~~~ // Controller中写入代码 $query = User::find(); $pagination = new Pagination(['totalCount' => $query->count(), 'defaultPageSize' => 2]); $models = $query->offset($pagination->offset)->limit($pagination->limit)->all(); return $this->render('test', [ 'models' => $models, 'pagination' => $pagination, ]); ~~~ 对应view代码 ~~~ <?php foreach ($models as $model): ?> <?= $model->id; ?> <?= $model->username; ?> <?= $model->email; ?> <br/> <?php endforeach; ?> <?php echo LinkPager::widget([ 'pagination' => $pagination, ]); ?> ~~~ #### 2.SQL方式 当单表无法满足需求时,就需要用到原生SQL进行实现,比如多表级联。 第1步 - SiteController 添加 actionTest() 方法 ~~~ public function actionTest(){ $connection = Yii::$app->db; $sql = "SELECT * FROM user"; $rows = $connection->createCommand($sql)->queryAll(); $pagination = new Pagination(['totalCount' => count($rows), 'defaultPageSize' => 2]); $models = $connection->createCommand($sql." limit ".$pagination->limit." offset ".$pagination->offset."")->queryAll(); return $this->render('test',[ 'models' => $models, 'pagination' => $pagination, ]); } ~~~ 对应view代码 ~~~ <?php use yii\widgets\LinkPager; ?> <?php foreach ($models as $model): ?> <?= $model['id']; ?> <?= $model['username']; ?> <?= $model['email']; ?> <br/> <?php endforeach; ?> <?php echo LinkPager::widget([ 'pagination' => $pagination, ]); ?> ~~~ > 后台经常使用到GridView,因为GridView自带检索、排序、增删改查,很适合后台使用,所以这里讲一讲和GridView的结合。 ### 二、 使用GridView #### 1.模型方式 ~~~ // Controller中写入代码 $dataProvider = new ActiveDataProvider([ 'query' => User::find(), ]); return $this->render('test', [ 'dataProvider' => $dataProvider, ]); } ~~~ 对应view代码 ~~~ <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'username', 'email', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> ~~~ #### 2.SQL方式 ~~~ // Controller中写入代码 $count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM user WHERE status=:status', [':status' => 1])->queryScalar(); //这里用的是SqlDataProvider,更多可参考([数据提供者](http://ihavenolimitations.xyz/wangking/yii2/211308)) $dataProvider = new SqlDataProvider([ 'sql' => 'SELECT * FROM user WHERE status=:status', 'params' => [':status' => 1], 'totalCount' => $count, 'pagination' => [ 'pageSize' => 20, ], ]); return $this->render('test', [ 'dataProvider' => $dataProvider, ]); ~~~ 对应view代码 ~~~ <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'username', 'email', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> ~~~