2014-11-21 70 views
1

我正在使用Laravel 4.2構建一個應用程序。我有一個units的模型和另一個users和數據透視表user_units。此應用程序中的每個用戶都可以選擇一個單元並將其添加到他最喜歡的列表中,然後他可以將該單元的信息作爲廣告發布。如何分頁Laravel中的對象數組?

我要選擇所有用戶

user_units(透視)表有以下幾列發佈的所有單位:

id 
user_id 
unit_id 
publish  
adtype  
addinfo   
created_at 
updated_at 

隨着模型關係方法

public function users() { 
    return $this->belongsToMany('User', 'user_units') 
       ->withPivot('id','publish', 'adtype', 'addinfo'); 
} 

public function units() { 
    return $this->belongsToMany('Unit', 'user_units') 
       ->withPivot('id','publish', 'adtype', 'addinfo'); 
} 

我的查詢選擇所有用戶發佈的所有單位

// Get all published units by users for sale. 
    $users = User::all(); 
    $publishedSaleUnits = []; 
    foreach($users as $user){ 
     $userUnits = $user->units()->orderBy('adtype', 'desc')->get(); 
     if(count($userUnits)){ 
      foreach($userUnits as $unit){ 
       if($unit->pivot->publish == 1 && $unit->unit_purpose_id == 1){ 
        if($unit->pivot->adtype){ 
         //push all featured ads onto the beginning of array 
         array_unshift($publishedSaleUnits, $unit); 
        }else{ 
         //push all normal ads onto the end of array 
         array_push($publishedSaleUnits, $unit); 
        } 
       } 
      } 
     } 
    } 

現在我得到了結果,但我不能使用分頁結果,因爲它是一個對象數組。

那麼有沒有更好的解決方案來獲取用戶分頁的所有出版單位?

回答

2

您的查詢數據的方法效率極低。在一個查詢中獲取數據。嵌套遍歷不僅難以閱讀,而且還是性能殺手。

要分頁問題:

Laravel提供了Pagignator廠。有了它,您將能夠用自己的數據構建自己的Paginator。

這是那麼容易,因爲

$units = Paginator::make($unit, count($unit), 10); 

,如果你使用的門面。否則Illuminate\Pagination\Factory是您正在尋找的課程。

+0

$單位=分頁程序::使($單位,計數($單位),10); 我嘗試這種方法之前,它創建$單位 - >鏈接()在視圖完美,但每個頁面包含$單位陣列的所有結果 – 2014-11-21 17:04:09

+0

我已經使用paginator :: make分頁$ publishSaleUnits數組中的記錄。但鑑於我正在獲取分頁鏈接,但所有鏈接都包含所有記錄。如何限制它到每頁項目。 – 2014-11-21 17:15:19

0

我得到了一個更好的解決方案進行分頁排列結果,我找到了答案here

Paginator::make功能,我們只需要而不是通過所有值所需的值。因爲paginator::make函數只顯示發送給它的數據。發送正確的偏移分頁數據到paginator::make,下面的方法應該遵循

$perPage = 5; 
    $page = Input::get('page', 1); 
    if ($page > count($publishedSaleUnits) or $page < 1) { $page = 1; } 
    $offset = ($page * $perPage) - $perPage; 
    $perPageUnits = array_slice($publishedSaleUnits,$offset,$perPage); 
    $pagination = Paginator::make($perPageUnits, count($publishedSaleUnits), $perPage); 
0

你可以試試我的代碼以自己的陣列,

$page = isset($request->page) ? $request->page : 1; // Get the page=1 from the url 
$perPage = $pagination_num; // Number of items per page 
$offset = ($page * $perPage) - $perPage; 

$entries = new LengthAwarePaginator(
    array_slice($contact_list, $offset, $perPage, true), 
    count($contact_list), // Total items 
    $perPage, // Items per page 
    $page, // Current page 
    ['path' => $request->url(), 'query' => $request->query()] // We 
     need this so we can keep all old query parameters from the url 
);