How to use pagination with laravel DB::select query

后端 未结 4 1027
醉梦人生
醉梦人生 2020-12-14 13:20

I am working on a project in Laravel and using DB facade to run raw queries of sql. In my case I am using DB::select, problem is that pagination method is not working with t

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 13:31

    Don't ever use the pagination logic on php-side! Use limit and offset on your sql's and leave the rest to the database server. Additional use a seperate count-select for your statement.

    Count:

    $sql_count = 'SELECT count(1) cnt FROM ('. $sql . ') x';
    $result = \DB::select( DB::raw($sql_count) );
    $data['count'] = $result[0]->cnt;
    

    Results:

    $sql .= ' LIMIT ' . $offset . ', ' . $limit; 
    
    $result = \DB::select( DB::raw($sql) );
    $myPaginator = new \Illuminate\Pagination\LengthAwarePaginator($result, $data['count'], $limit, $page, ['path' => action('MyController@index')]);
    $data['result'] = $result;
    

提交回复
热议问题