2014-02-08 38 views
0

我試圖加載列表數據庫中的所有項目,同時應用可選篩選器(如果指定了它們)。有了這些,我想加載每個列表的訂閱者數量。我可以通過在視圖中的foreach循環中正常的$ list-> subscribers() - > count()調用來做到這一點,但我可以通過實際的分頁功能來做到這一點嗎?Laravel Eager加載與Eloquent的關係

裏面我ListsRepo.php文件:

<?php namespace Acme\Repos; 

    use Lists; 

    class DbListsRepo implements ListsRepoInterface { 

     public function getPaginated(array $params) 
     { 
      $list = new Lists; 

      // See if there are any search results that need to be accounted for 
      if ($params['search'] != null) $list = $list->where('name', 'LIKE', "%".$params['search']."%"); 

      // See if we need to restrict the results to a single user 
      if ($params['user'] != null) $list = $list->where('userID', $params['user']); 

      // Check if the data should be sorted 
      if ($this->isSortable($params)) $list = $list->orderBy($params['sortBy'], $params['direction']); 

      return $list->paginate(10); 
     } 

     public function isSortable(array $params) 
     { 
      return $params['sortBy'] and $params['direction']; 
     } 

    } 

裏面我index.blade.php文件:

.... 
@if ($lists->count()) 
    @foreach ($lists as $list) 
     <tr> 
      <td><h4>{{ $list->name }}</h4></td> 
      <td><p>{{ $list->subscribers()->count() }}</p></td> 
     </tr> 
    @endforeach 
@endif 
... 

那麼,有沒有辦法正確安裝的用戶數到我getPaginated功能?目前的實施導致N + 1情景。

回答

1

您應該能夠通過在您getPaginated功能的渴望負荷做到這一點:

public function getPaginated(array $params) { 
    $list = Lists::newQuery(); 

    // See if there are any search results that need to be accounted for 
    if ($params['search'] != null) $list->where('name', 'LIKE', "%".$params['search']."%"); 

    // See if we need to restrict the results to a single user 
    if ($params['user'] != null) $list->where('userID', $params['user']); 

    // Check if the data should be sorted 
    if ($this->isSortable($params)) $list->orderBy($params['sortBy'], $params['direction']); 

    $list->with('subscribers'); 

    return $list->paginate(10); 
} 

然後在你的刀片,你可以簡單地做count($list->subscribers)因爲用戶將被預裝到您的列表模式。

當需要加載時,您必須在結果數組上使用PHP的count(),而不是SQL的COUNT,因爲在相關表上使用單個select語句完成加載。