【问题标题】:How would paginate a json response in my GET request without the use of models/databases?在不使用模型/数据库的情况下,如何在我的 GET 请求中对 json 响应进行分页?
【发布时间】:2022-02-11 05:46:08
【问题描述】:

我想知道如何在不使用数据库/模型的 GET 请求中使用给定的 response 对 10 的倍数进行分页。

我已经四处搜索,但我主要看到的是数据库/模型分页的示例,而不是 json 响应分页的示例。

以下是我尝试过的方法(以及许多其他方法,但我已经没有选择余地并碰壁了)但无济于事。

我知道有一种简单的方法可以做到这一点,但我似乎无法理解它。任何反馈将不胜感激:)。

$response = Http::get(env('endpoint'), $queryParams);

$results = $response->json()['results'];

$numResults = $response->json()['num_results']; 

$results->paginate(10); // multiples of ten.  I know this is the Model way of doing it but I can't find any other way to achieve this.

【问题讨论】:

  • @HashtagForgotName 我根本没有使用模型。这是我仅使用的简单 GET 请求。这是通过使用模型来显示的。
  • Illuminate\Contracts\Support\Jsonable Interface contract and expose the toJson method, so it's very easy to convert your pagination results to JSON. 您可以将任何分页结果转换为 json 响应您不需要模型,只需要您的分页结果
  • 像这样DB::table('users')->paginate(15) 然后在它后面探测->toJson() 所以像这样DB::table('users')->paginate(15)->toJson()
  • @HashtagForgotName 非常感谢您的反馈,但我没有使用数据库。这是来自端点的 json 响应。我想对 JSON 响应进行分页。根本没有数据库。

标签: php laravel debugging pagination


【解决方案1】:

您可以收集信息:

collect($results)

然后分页使用 ->skip(number_to_skip) 然后 ->take(number_to_take);

然后就像你正在做的那样返回它。 它会是这样的:

$page = $request->page;
$take = 10;
$skip = ($page - 1) * $take;
$resultsCount = collect($results)->count();
$results = collect($results)->skip($skip)->take($take)->all();

【讨论】:

  • 感谢乔丹的回复!请您提供您所指的代码示例,好吗? :)
  • 我在响应中添加了代码示例。
  • 知道了,谢谢。我假设$page 是结果总数,对吧?
  • $take 将是结果的数量。 $page 将是用户所在的页面。上下文化:如果他在第 1 页,我们将跳过 0 项并获得 10。如果他在第 2 页,我们将跳过 10 项并获得 10 多个。
  • 我们不需要考虑 GET 响应中存在的结果总数吗?
【解决方案2】:

也许你可以使用de chunk的收集方法

$results = collect($result);
$outputs = $results->chunck(20)[$request->input('page')];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多