2014-11-08 62 views
0

我試圖在laravel.Checking的laravel文檔創建原始查詢手動分頁,我看到使用方法分頁程序,如:`原始查詢的手動分頁laravel

$申請人=分頁程序::使($申請人,$ totalApplicants,4);`

但是,當我返回$申請人它給我所有的記錄,而不是我的Paginator :: make方法所要求的4,但如果我打電話給我的申請人的鏈接()mehod像:$ applicants-> links()它返回到我的視圖的分頁鏈接

請問我做錯了什麼,或者我需要寫一個mehod使這項工作

從我的控制器代碼:

$statement3 = "SELECT * FROM applicant where lga = '$appulga' "; 

     //loop through lga id to build query 
     foreach($LGA_Names as $lga) 
     { 
      $statement3.= " "."OR"." "."lga=". "'".$lga."'"; 
     } 

     //FAcility for User assigned LGA 
     $applicants = DB::Select($statement3); 
     /////////////////////////////////////////////////////////////// 
     $totalApplicants = count($applicants); 
     $perpage = 4; 

     $applicants = Paginator::make($applicants,$totalApplicants,$perpage); 
+0

你能分享更多的代碼嗎? '$ applicants'必須是數組 – knpsck 2014-11-08 13:32:05

+0

只是從我的控制器 – 2014-11-08 13:38:03

回答

1

分頁程序不分裂的集合,你必須手動處理結果。

$page = Paginator::getCurrentPage(); // Get the current page for the request 

$limit = 4; 
$offset = $page * $limit; 

// query to get `COUNT(*)` 
// query to get results with `LIMIT $offset, $limit` 

Paginator::make($results, $total, $limit); 

手動編寫sql查詢手動無效且不安全,改爲使用查詢生成器;

$query = DB::table('applicant')->where('lga', $appulga); 

foreach ($LGA_Names as $lga) 
{ 
    $query->orWhere('lga', $lga); 
} 

$applicants = $query->paginate(4); 
+0

共享代碼實際上我的查詢比你看到它更復雜。我必須根據用戶登錄ID生成lga,然後從設施數據庫生成設施,然後從申請人表中生成最終申請人。所以使用雄辯的查詢是我的選擇 – 2014-11-08 14:39:38

1

你已經獲得了所有記錄,因爲你叫Paginator::make$applicants,您可以嘗試這樣的事:

$pageNumber = Input::get('page', 1); 
$perpage = 4; 


$statement = "SELECT * FROM applicant where lga = '$appulga' "; 
// ... 
$applicants = DB::Select($statement); 


$slice = array_slice($applicants, $perpage * ($pageNumber - 1), $perpage); 
$applicants = Paginator::make($slice, count($applicants), $perpage); 
1

分頁程序計算分頁的鏈接,所以它不會影響您的查詢。

它只返回/Illuminate/Pagination/Paginator對象,如果你想返回作爲響應或傳遞來查看,它將返回在toArray方法中定義的數組元素。