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情景。