## 练习
考虑实现分页查找的功能
~~~
http://localhost:8000/index.php?s=/book/getBookList/page/1/pageSize/5
~~~
返回数据格式:
~~~
{
"errno": 0,
"errmsg": "",
"data": {
"count": 2,
"totalPages": 1,
"pageSize": 10,
"currentPage": 1,
"data": [
{
"id": "1",
"title": "ThinkPHP 5框架原理与实战 ",
"author": "黑马程序员",
"publisher": "中国铁道出版社",
"pub_year": "2019",
"isbn": "9787113259716",
"price": "55.00"
},
{
"id": "2",
"title": "ThinkPHP 5实战 ",
"author": "夏磊",
"publisher": "清华大学出版社",
"pub_year": "2019",
"isbn": "9787302533580",
"price": "49.00"
}
]
}
}
~~~
参考解答:
~~~
public function getBookList($page = 1, $pageSize = 10)
{
// 获取数据集
$books = Db::name('book')->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $pageSize]);
$books = $books->toArray();
//转换分页器满足约定的接口规范
$data = array(
'count' => $books['total'],
'currentPage' => $books['current_page'],
"pageSize" => $books['per_page'],
"totalPages" => $books['last_page'],
"data"=>$books['data']
);
$response = [
'errno' => 0,
'errmsg' => '',
'data' => $data
];
return json($response);
}
~~~