2016-09-28 95 views
0

如何在此查詢中使用paginate()?Laravel Paginate與DB :: raw查詢的用法

$result = DB::select(DB::raw(" select a.user_id, a.user_email, 
a.user_account_status, a.created_at, b.s_account_limit AS account_limit, 
c.consumed_limit, ((b.s_account_limit*1024) - c.consumed_limit) AS 
remaining_limit FROM upload_limits as b, users AS a JOIN user_upload_limits as 
c WHERE (a.user_id=c.user_id) AND a.user_type='Simple'")); 
+0

的可能的複製[如何使用Laravel5原始的SQL分頁?](http://stackoverflow.com/questions/29968354/how-to-use-raw -SQL-分頁-in-laravel5) –

+0

簡答:您無法在Laravel中分頁查詢原始查詢,但有解決方法。 –

+0

$ pagination = Paginator :: make($ book,count($ book),5); –

回答

2

您可以使用->paginate()方法,或者如果你想手動創建一個分頁,你會做這樣的事情:

$perPage = $request->input("per_page", 10); 
$page = $request->input("page", 1); 
$skip = $page * $perPage; 
if($take < 1) { $take = 1; } 
if($skip < 0) { $skip = 0; } 

$basicQuery = DB::select(DB::raw(" select a.user_id, a.user_email, a.user_account_status, a.created_at, b.s_account_limit AS account_limit, c.consumed_limit, ((b.s_account_limit*1024) - c.consumed_limit) AS remaining_limit FROM upload_limits as b, users AS a JOIN user_upload_limits as c WHERE (a.user_id=c.user_id) AND a.user_type='Simple'")); 
$totalCount = $basicQuery->count(); 
$results = $basicQuery 
    ->take($perPage) 
    ->skip($skip) 
    ->get(); 

$paginator = new \Illuminate\Pagination\LengthAwarePaginator($results, $totalCount, $take, $page); 

return $paginator; 
+0

謝謝;非常感激。 –

0

您還可以添加您在陣列結果通過自定義排序方法DB的::您的PARAMS沿着原料:

public function sort($array_of_objects, $sort_by=null, $order, $page) 
{ 
    $collection = collect($array_of_objects); 
    if ($sort_by) 
    { 

     if ($order=='desc') { 
      $sorted = $collection->sortBy(function($role) use ($sort_by) 
      { 
       return $role->{$sort_by}; 
      })->reverse(); 
     } else if ($order=='asc') { 
      $sorted = $collection->sortBy(function($role) use ($sort_by) 
      { 
       return $role->{$sort_by}; 
      }); 
     } 
    } else { 
     $sorted = $collection; 
    } 

    $num_per_page = 20; 
    if (!$page) { 
     $page = 1; 
    } 

    $offset = ($page - 1) * $num_per_page; 
    $sorted = $sorted->splice($offset, $num_per_page); 

    return new Paginator($sorted, count($array_of_objects), $num_per_page, $page); 

}