【问题标题】:How to build a pagination API in Yii 1.x using CPagination如何在 Yii 1.x 中使用 CPagination 构建分页 API
【发布时间】:2015-07-10 19:02:02
【问题描述】:

我是 yii 的新手。目前我正在为某个项目构建一个 API。我设法从数据库中获取所有数据并作为响应发送到前端。现在有一个增强功能,我应该限制每页输出的结果。所以分页。我在 yii 中阅读了很多关于 CPagination 的内容,无论我尝试什么,我都会收到 500 内部服务器错误。这是我的代码;

    public function actionIndex()
{
    //getting page number from front end
    $request = file_get_contents('php://input');

    if (is_null($request)) {
        $page = 1;
    } else {
        $input = json_decode($request, true);
        $page = $input['page'];
    }

    //Criteria sorting templates by id DESC
    $criteria = new CDbCriteria;
    $criteria->order = 'id DESC';

    //Number of rows returned
    $count = TblTemplate::model()->count($criteria);

    //Templates per page
    $perPage = 2;

    //Calculating the offset
    $offset = ($page > 1) ? ($page * $perPage) - $perPage : 0;

    $pages = new CPagination($count);
    $pages->pageSize = $perPage;
    $pages->offset   = $offset;
    $pages->applyLimit($criteria);

    //fetching all templates    
    $templates = TblTemplate::model()->findAll($criteria);

    $response = [];

    //Fetching all array - filtering through the cluster
    foreach ($templates as $template) {
        $response[] = [
            'id'      => $template->id,
            'name'    => $template->name,
            'email'   => $template->email,
            'content' => $template->content 
        ];
    }

    echo json_encode($response);
}

感谢您的帮助。

【问题讨论】:

  • 为什么不在CDbCriteria 中尝试offsetlimit
  • 让我试试,但是从 yii 文档中 pageSize 和 offset 必须在 Cpagination 的对象上
  • 我在条件中添加了偏移量,但偏移量不起作用

标签: php yii pagination


【解决方案1】:

改成:-

    $perPage = 2;
    $offset = ($page > 1) ? ($page * $perPage) - $perPage : 0;

    $criteria = new CDbCriteria;
    $criteria->order = 'id DESC';
    $criteria->limit=$perPage;
    $criteria->offset=$offset;

    $templates = Users::model()->findAll($criteria);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2019-06-30
    • 1970-01-01
    相关资源
    最近更新 更多