How to use pagination with laravel DB::select query

后端 未结 4 1008
醉梦人生
醉梦人生 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:29

    This is suitable for me

    $sql = "some sql code";
    
    $page = 1;
    $size = 10;
    $data = DB::select($sql);
    $collect = collect($data);
    
    $paginationData = new LengthAwarePaginator(
                             $collect->forPage($page, $size),
                             $collect->count(), 
                             $size, 
                             $page
                           );
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-14 13:36

    Try:

    $notices = DB::table('notices')
            ->join('users', 'notices.user_id', '=', 'users.id')
            ->join('departments', 'users.dpt_id', '=', 'departments.id')
            ->select('notices.id', 'notices.title', 'notices.body', 'notices.created_at', 'notices.updated_at', 'users.name', 'departments.department_name')
            ->paginate(20);
    
    0 讨论(0)
  • 2020-12-14 13:36
    public function index(Request $request){
    
    $notices = DB::select('select notices.id,notices.title,notices.body,notices.created_at,notices.updated_at,
    users.name,departments.department_name
    FROM notices
    INNER JOIN users ON notices.user_id = users.id
    INNER JOIN departments on users.dpt_id = departments.id
    ORDER BY users.id DESC');
    
    $notices = $this->arrayPaginator($notices, $request);
    
    return view('welcome')->with('allNotices', $notices);
    
    }
    
    public function arrayPaginator($array, $request)
    {
        $page = Input::get('page', 1);
        $perPage = 10;
        $offset = ($page * $perPage) - $perPage;
    
        return new LengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array), $perPage, $page,
            ['path' => $request->url(), 'query' => $request->query()]);
    }
    
    0 讨论(0)
提交回复
热议问题