琯琯博客 纸上得来终觉浅,绝知此事要躬行。

Yii2 学习笔记之分页

琯琯
2017-03-23
PHP  Yii
 

一、使用LinkPager

1.1 模型方式

<?php
// 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,
]); ?>

1.2 SQL方式

当单表无法满足需求时,就需要用到原生SQL进行实现,比如多表级联。 第1步 - SiteController 添加 actionTest() 方法

<?php
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

2.1 模型方式

<?php
// Controller 中写入代码
$dataProvider = new ActiveDataProvider([
	'query' => User::find(),
]);

return $this->render('test', [
	      'dataProvider' => $dataProvider,
    ]);

对应view代码

<?php
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'username',
        'email',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

2.2 SQL方式

<?php
// Controller中写入代码
$count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM user WHERE status=:status', [':status' => 1])->queryScalar();

// 这里用的是SqlDataProvider,更多可参考([数据提供者](http://www.kancloud.cn/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代码

<?php
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'username',
        'email',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

(完)


相关文章

评论

内容导航