lumen 6:如何在 lumen 上重构响应分页的数据?

Posted

技术标签:

【中文标题】lumen 6:如何在 lumen 上重构响应分页的数据?【英文标题】:lumen 6 : how to restructure data of response pagination on lumen? 【发布时间】:2020-06-20 23:24:51 【问题描述】:

我花了很多时间来解决这个问题,我如何用流明重构响应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/"
         
       
    ]

我该怎么办?

【问题讨论】:

【参考方案1】:

其实很简单。

您可以返回以下内容,而不是返回 $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
    ]);

【讨论】:

@Alfiyanm 不需要 Response 类,我已经更新了我的答案以使用 response() helper。 @Alfiyanm count($colletion)Person::count() 相同

以上是关于lumen 6:如何在 lumen 上重构响应分页的数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 LUMEN 中使用 GATE 立面(Laravel 6.2)

如何在 Lumen 中应用分页?

Lumen 在发布时给出带有 500 内部错误的空白页

InvalidArgumentException,“未找到视图”,在 Lumen 5.2.6 上

在多个文件中拆分 Lumen 6.X 路由

Lumen 主页在 AWS 上正常工作,但其他页面不可用