ThinkPHP5前后端分离分页实现概述
本内容详解了在基于ThinkPHP5构建的前后端分离架构中,如何高效实现数据列表的分页展示功能。以下提供两种主流实现思路及其具体代码示例,供开发者参考与实践。
第一种实现路径
借助ThinkPHP5内置的paginate方法,系统可自动完成分页参数的解析、SQL查询构造以及分页元数据的生成,极大简化开发流程。
关键参数说明
page:当前页码,paginate方法会自动从请求中捕获该值,无需手动提取。
size:每页显示的数据条数,用于控制分页粒度。
核心代码实现
/**
* Notes:消费记录
* Date: 2026/6/25
* Time: 15:43
* @param Request $request
* @return \think\response\Json
*/
public function getMyConsumeLog(Request $request)
{
global $_W;
$size = $request->param('size', 6);
$list = $this->model->getListByMid($_W['user']['id'],$size);
return json(['data' => $list, 'error' => 0, 'message' => 'success']);
}
public function getListByMid($mid,$size = 10){
$res = $this
->alias('c')
->field('c.*,b.book_name,b.book_flash,s.section_title')
->leftJoin('booksection s','c.chapter_id = s.id')
->leftJoin('book b','s.book_id = b.id')
->where('c.mid',$mid)
->order('c.id desc')
->paginate($size);
return $res;
}
该方法执行后返回的标准数据结构如下所示
{ "data": { "total": 1, "per_page": 1, "current_page": 1, "last_page": 1, "data": [ { "id": 105, "mid": 55, "book_id": 31, "chapter_id": 46046, "score": 27, "create_time": 1561447448, "book_name": "桃运村支书", "book_flash": "https://cdnxiaoshuo.t.com/FiO6TM0N4kpzKB7tqrDko64ZS4H4", "section_title": "第29章 康庄大道" } ] }, "error": 0, "message": "success" }
第二种实现路径
通过手动调用limit方法配合偏移量计算,开发者可以更灵活地控制查询过程,适用于需要自定义返回字段或复杂聚合的场景。
$curr_page = $request->param('page', 1);
$size = $request->param('size', 6);
$list = $consume_model->getListByWhere($curr_page, $size, $where);
$num = $consume_model->getListByWhereCount($where);
return json(['data' => $list,'num' => $num,'error' => 0, 'message' => 'success']);
public function getListByWhere($curr_page,$limit = 10,$where = null){
$res = $this
->alias('c')
->field('c.*,b.book_name,s.section_title')
->leftJoin('booksection s','c.chapter_id = s.id')
->leftJoin('book b','s.book_id = b.id')
->where($where)
->order('c.id desc')
->limit($limit*($curr_page - 1),$limit)
->select()
->toArray();
return $res;
}
public function getListByWhereCount($where = null){
$count = $this
->alias('c')
->where($where)
->count();
return $count;
}
此方式返回的数据结构通常包含具体的记录列表及额外的统计信息,示例如下
{ "data": [ { "id": 2, "mid": 4, "book_id": 4, "chapter_id": 22, "score": 30, "create_time": 0, "book_name": "复仇者联盟I", "section_title": "第11章 你是睡" }, { "id": 1, "mid": 4, "book_id": 29, "chapter_id": 34, "score": 20, "create_time": 1598999, "book_name": "复仇者联盟II", "section_title": "第11章 你是睡" } ], "num": 2, "total_coin": 50, "error": 0, "message": "success" }
希望上述关于ThinkPHP5框架下PHP程序设计的分页技巧能为相关项目的开发提供有益参考。