如何在Laravel中将集合或自定义查询分页到API json中? [英] How do I paginate a collection or custom query into API json in Laravel?

查看:451
本文介绍了如何在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?

推荐答案

我将其保存在app \ Core \ Helpers类中,以便可以从任何地方调用\ App \ Core \ Helpers :: makePaginatorForCollection($ query_results) .最可能使用它的地方是处理复杂查询的控制器的最后一行.

I keep this in an app\Core\Helpers class so that I can call them from anywhere as \App\Core\Helpers::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 \App\Core\Helpers::makePaginatorForCollection($result);
}

在app \ Core \ Helpers.php或您希望自动加载的任何位置.

In app\Core\Helpers.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 \Illuminate\Support\Collection $collection
 *
 * @return \Illuminate\Pagination\LengthAwarePaginator
 */
public static function makePaginatorForCollection(\Illuminate\Support\Collection $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 \Illuminate\Pagination\LengthAwarePaginator(array_values($page_data), count($collection), $per_page);
}

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

    return self::makePaginatorForCollection($collection);
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆