如何使用 CPagination 在 Yii 1.x 中构建分页 API
How to build a pagination API in Yii 1.x using CPagination
我是 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);
}
感谢您的帮助。
将其更改为:-
$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);
我是 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);
}
感谢您的帮助。
将其更改为:-
$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);