2017-07-10 15 views
0

出力をページ設定する特定のモデルテーブルに基づいていない複雑なクエリがあります。しかし、ラーベールはモデルやテーブルに依存しています。どのようにしてコレクションにページを分け、出力がlaravelのページ区切り出力形式と一致するようにすることができますか?LaravelのAPI jsonにコレクションまたはカスタムクエリをページ分割するにはどうすればよいですか?

+0

https://laravel.com/docs/5.4/pagination#manually-creating-a-paginatorを確認しましたか? – tompec

+0

はい、コードサンプルはありませんでした。だから私は次の人のために物事をより簡単にするための答えでこの質問を投稿しました。 –

答えて

0

私はどこでも\ App \ Core \ Helpers :: makePaginatorForCollection($ query_results)として呼び出すことができるように、これをapp \ Core \ Helpersクラスに保存します。これを使用する最も可能性の高い場所は、複雑なクエリを処理するコントローラの最後の行です。アプリ/ HTTP /コントローラ/ simpleExampleController.php

アプリ\コア\ Helpers.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); 
} 
関連する問題