如何在 Laravel 中将集合或自定义查询分页到 API json 中?

编程入门 行业动态 更新时间:2024-10-27 13:21:56
本文介绍了如何在 Laravel 中将集合或自定义查询分页到 API json 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的查询,它不基于我想要为输出分页的任何特定模型表.然而,laravel 的内置分页依赖于模型和表格.如何对集合进行分页并使输出与 Laravel 的内置分页输出格式相匹配?

I have a complex query that is not based on any specific model table that I want to paginate output for. However laravel's built in pagination relies on models and tables. How can I paginate a collection and have the output match up with laravel's built in pagination output format?

推荐答案

我将它保存在 appCoreHelpers 类中,以便我可以从任何地方以 AppCoreHelpers::makePaginatorForCollection($query_results) 的形式调用它们.最有可能使用它的地方是处理复杂查询的控制器的最后一行.

I keep this in an appCoreHelpers class so that I can call them from anywhere as AppCoreHelpers::makePaginatorForCollection($query_results). The most likely place to use this is the last line of a controller that deals with complex queries.

在 app/Http/Controllers/simpleExampleController.php 中

In app/Http/Controllers/simpleExampleController.php

/**
 * simpleExampleController
 **/
public function myWeirdData(Request $request){
    $my_unsafe_sql = '...';//never do this!!
    $result = DB::statement(DB::raw($my_unsafe_sql));
    return AppCoreHelpers::makePaginatorForCollection($result);
}

在 appCoreHelpers.php 或任何你喜欢自动加载的地方.

In appCoreHelpers.php or anywhere you like that auto loads.

/**
 * This will match laravel's built in Model::paginate()
 * because it uses the same underlying code.
 *
 * @param IlluminateSupportCollection $collection
 *
 * @return IlluminatePaginationLengthAwarePaginator
 */
public static function makePaginatorForCollection(IlluminateSupportCollection $collection){
    $current_page = (request()->has('page')? request()->page : 1) -1;//off by 1 (make zero start)
    $per_page = (request()->has('per_page')? request()->per_page : config('api.pagination.per_page')) *1;//make numeric
    $page_data = $collection->slice($current_page * $per_page, $per_page)->all();

    return new IlluminatePaginationLengthAwarePaginator(array_values($page_data), count($collection), $per_page);
}

/**
 * Copy and refactor makePaginatorForCollection()
 * if collection building is too slow.
 *
 * @param $array
 *
 * @return IlluminatePaginationLengthAwarePaginator
 */
public static function makePaginatorForArray($array){
    $collection = collect($array);

    return self::makePaginatorForCollection($collection);
}

这篇关于如何在 Laravel 中将集合或自定义查询分页到 API json 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-26 23:29:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/670255.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分页   自定义   中将   如何在   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!