2014-02-08 10 views
0

목록 필터가 지정된 경우 해당 필터를 적용하면서 모든 목록을 데이터베이스에서로드하려고합니다. 이것들과 함께 각 목록에 대한 가입자 수를로드하고 싶습니다. 뷰에서 foreach 루프 내에서 일반 $ list-> subscribers() -> count() 호출을 통해이 작업을 수행 할 수 있지만 실제 페이지 매김 함수를 통해이 작업을 수행 할 수 있습니까? 내 index.blade.php 파일의 내부Laravel Eager Eloquent를 사용하여 관계로드하기

<?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']; 
     } 

    } 

: 내 ListsRepo.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) 할 수 있습니다.

열의 로딩은 관련 테이블의 단일 select 문으로 수행되므로 PHP의 count()를 결과 배열에 사용해야하며 SQL의 COUNT는 열거하지 않아야합니다.

관련 문제