【问题标题】:merge custom meta data to paginated response in laravel将自定义元数据合并到 laravel 中的分页响应
【发布时间】:2018-09-05 22:07:19
【问题描述】:

我的控制器中有以下代码:

公共函数索引(SaleRequest $request, $id) {

    try {
        $from = Carbon::parse($request->query->get('from', '1970-01-01'));
        $till = Carbon::parse($request->query->get('till', Carbon::now()))->endOfDay();
    } catch (\Exception $e) {
        return response()->json([
            'error' => 'Invalid time range or data',
        ], 400);
    }

    $includes = ['product', 'price'];

    $seller = $this->resellerRepository->findOrFail($id);

    $paginator = $this->parseRequest($request, $seller)->with($includes)->paginate();

    $sales = $paginator->items();

    $data = fractal()
        ->collection($sales, new SaleTransformer())
        ->parseIncludes($includes)
        ->paginateWith(new IlluminatePaginatorAdapter($paginator))
        ->toArray();

    $sum = 0;
    foreach ($sales as $sale) {
        $sum = $sum + $sale->price->value_origin;
    }

    $data['meta'] = [
        'from'          => $from->toDateString(),
        'till'          => $till->toDateString(),
        'count_total'   => count($data['data']),
        'total'         => $sum / 100,
    ];

    return response()->json($data);
}

在我的回复中,我没有从分页器获得分页元数据。我只得到自定义元数据:

"meta": {
    "from": "1970-01-01",
    "till": "2018-09-05",
    "count_total": 5,
    "total": 80
}

我的方法是手动将分页数据添加到元中,例如:

    $data['meta'] = [
        'from'          => $from->toDateString(),
        'till'          => $till->toDateString(),
        'count_total'   => count($data['data']),
        'total_sum'         => $sum / 100,
        'pagination' => [
            'current_page' => $paginator->currentPage(),
            'last_page' => $paginator->lastPage(),
            'total' => $paginator->total(),
            'count' => $paginator->count(),
            'per_page' => $paginator->perPage(),
        ]
    ];

有没有更好的方法来做到这一点?

提前致谢!

【问题讨论】:

  • 在添加自定义“元”索引之前您会得到什么?您似乎还覆盖了元索引。你本来可以做到的,$data['meta']['from'] = $from->toDateString() 等等,不是吗?

标签: php laravel pagination


【解决方案1】:

答案是更新我的 ide_helper 方法,因为 Fractal 有一个方法 addMeta() 。

    $data = fractal()
        ->collection($items, new ItemTransformer())
        ->paginateWith(new IlluminatePaginatorAdapter($paginator))
        ->addMeta([
            'from' => $from->toDateString(),
            'till' => $till->toDateString(),
            'total_sum' => $totalSum,
            'page_sum' => $sum,
        ])
        ->toArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-04
    • 2014-07-04
    • 2016-01-31
    • 1970-01-01
    • 2016-09-21
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多