[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'],
],
]); ?>
~~~
- 基础教程
- 入门安装
- Yii2 composer 安装慢解决
- Cookies
- 数据库操作
- 数据提供者
- 助手类
- 验证规则
- GridView
- DetailView
- YII2分页
- JS、CSS的引用
- Excel导出
- 中文转拼音
- 发送邮件
- 第三方插件
- Session跨域共享
- Url跨域访问
- 场景应用
- 查询条件链
- Session分布式共享
- Redis的使用
- mongodb
- 高级教程
- 自定义gii模板
- 角色权限管理(RBAC)
- user组件的配置
- 国际化(I18N)
- 小部件(Widget)
- 模块(Module)
- 行为(Behavior)
- 缓存(Cache)
- migrate 数据库迁移
- phpstorm
- 快捷键
- 自定义
- 其它插件