Laravel Eager用Eloquent加载关系

时间:2014-02-08 05:55:11

标签: php laravel laravel-4 eloquent

我正在尝试加载我的列表数据库中的所有项目,同时应用可选过滤器(如果已指定)。有了这些,我想加载每个列表的订阅者数量。我可以通过视图中foreach循环中的普通$ list-> subscribers() - > count()调用来完成此操作,但是我可以通过实际的分页函数执行此操作吗?

在我的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 个答案:

答案 0 :(得分:1)

您应该可以通过在getPaginated函数中包含eager-load来实现:

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语句进行了急切加载。