[英]lumen 6 : how to restructure data of response pagination on lumen?
I have spend many time to solve this problem, How do i resctructure data of response json pagination with lumen?我花了很多时间来解决这个问题,我如何使用 lumen 重新构建响应 json 分页的数据? which should i use between API resources and transformer?
我应该在 API 资源和转换器之间使用哪个? of Illuminate pagination?
的 Illuminate 分页?
My PersonController, which i try to use LengthAwarePagination我的 PersonController,我尝试使用 LengthAwarePagination
use App\Model\Person;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
public function index(Request $request)
{
$results = Person::all();
$data = array();
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$collection = new Collection($results);
$per_page = 1;
$currentPageResults = $collection->slice(($currentPage-1) * $per_page, $per_page)->all();
$data = new LengthAwarePaginator($currentPageResults, count($collection), $per_page);
$data->setPath($request->url());
return $data;
}
Actual response实际反应
{
"current_page": 1,
"data": [
{
"id": 1,
"type": "persons",
"attributes": {
"name": "andrew",
"country": "new zealand",
"gender": "male"
},
}
],
"first_page_url": "http://localhost:8000/person?page=1",
"from": 1,
"last_page": 50,
"last_page_url": "http://localhost:8000/person?page=50",
"next_page_url": "http://localhost:8000/person?page=2",
"path": "http://localhost:8000/person",
"per_page": 1,
"prev_page_url": null,
"to": 1,
"total": 50
}
but the response I expected但我期待的回应
{
"meta": {
"count": 5,
"total": 20
},
"links": {
"first": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=0",
"last": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=10",
"next": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=10",
"prev": "null"
},
"data": [
{
"type": "persons",
"id": "1",
"attributes": {
"name": "andrew",
"country": "new zealand",
"gender": "male"
},
"links": {
"self": "http:localhost:8000/api/v1/persons/1/"
}
}
]
}
What should I do?我该怎么办?
Instead of returning $data
you can return something like this:您可以返回如下内容,而不是返回
$data
:
return response()->json([
'meta' => [
"count" => count($collection),
"total" => $data->total
],
'links' => [
"first" => $data->first_page_url,
"last" => $data->last_page_url,
"next" => $data->next_page_url,
"prev" => $data->prev_page_url
],
'data' => $data->data
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.