内腔6:如何重组内腔响应分页的数据?

问题描述 投票:1回答:1

我花了很多时间来解决这个问题,如何用流明重构响应json分页的数据?我应该在API资源和转换器之间使用哪个?分页?

我的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;
}

实际回答

{
    "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
}

但我希望得到答复

{
    "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/"
         }
       }
    ]
}

我该怎么办?

laravel rest api lumen
1个回答
0
投票

实际上非常简单。

代替返回$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
    ]);
© www.soinside.com 2019 - 2024. All rights reserved.