代码之家  ›  专栏  ›  技术社区  ›  Tarek Adam

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

  •  0
  • Tarek Adam  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Tarek Adam    7 年前

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

    在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);
    }
    

    /**
     * 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);
    }