Yii2——restful API 数据分页

Yii 的文档,如果没有完整的看完,真的不好发挥它的威力。

先看看这一节:Yii 2.0 权威指南 - RESTFUL WEB 服务 - 快速入门

这里写了逐页列出,有的时候还真的忽略了,毕竟示例里就几个数据,哪看得出来分页。

设置分页

时间有限,用一个Controller记录下算了:

<?php
namespace frontend\controllers;


use common\models\Book;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\rest\ActiveController;

class BookController extends ActiveController
{
    public $modelClass = "common\models\Book";

    public function actions()
    {
        $actions = parent::actions();
        unset(
            $actions['index']
        );

        return $actions;
    }

    // 重写 $actions['index']
    public function actionIndex()
    {
        return new ActiveDataProvider([
            'query' => Book::find(),
            // 设置分页,比如每页200个条目
            'pagination' => new Pagination(['pageSize' => 200])
        ]);
    }
}

输出分页信息

可以输出诸如 nextLinklastLink 这类信息,分别表示下一页数据的访问链接和上一页数据的访问链接,还可以输出分页大小、本页页码、数据条目总数等信息。

具体的网上很多,不再赘述。

猜你喜欢

转载自www.cnblogs.com/alanabc/p/9729026.html