繁体   English   中英

Laravel渴望与雄辩的人建立关系

[英]Laravel Eager Loading a Relation with 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场景。

您应该可以通过在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语句完成的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM