如何在没有N+1问题的情况下计算雄辩的关系并加载整个模型


How to count eloquent relationship without the N+1 issue and loading the entire model?

我显示了一个类别列表,以及每个类别中的文章数。我得到了预期的结果,但我有N+1的问题。

我的CategoriesController索引函数:

public function index()
{
    return View::make('categories.index', [
        'articleCategories' => Category::where('type', 'articles')->orderBy('name')->get(),
    ]);
}

Category模型与文章有许多关系:

public function articles()
{
    return $this->hasMany('Article');
}

我的categories.index视图:

@foreach($articleCategories as $articleCategory)
    <p>
    {{ HTML::link(URL::route('articles.category', array('category' => Str::slug($articleCategory->name))), $articleCategory->name) }}
    {{ $articleCategory->articles->count() }}
    </p>
@endforeach

编辑:如果我渴望加载所有相关文章,它会起作用,但由于我只需要文章计数pr类别,这似乎有些过头了。急于加载文章和->count()会影响性能吗?或者这是最好的方法吗?

// helper relation
public function articlesCount()
{
    return $this->hasOne('Article')->selectRaw('category_id, count(*) as aggregate')->groupBy('category_id');
}
// and accessor for fetching it easier
public function getArticlesCountAttribute()
{
    if ( ! array_key_exists('articlesCount', $this->relations)) $this->load('articlesCount');
    return $this->getRelation('articlesCount')->aggregate;
}

然后你可以这样做:

// eager load in single query
$categories = Category::with('articlesCount')->get();
// thanks to accessor this will return value and load relation only if needed
$categories->first()->articlesCount;

试试这个

public function index()
{
    return View::make('categories.index', [
        'category' => Category::with('articles')->where('type', 'articles')->orderBy('name')->get(),
    ]);
}

现在在视图中获取类别数据只需进行

$category->type,或者如果你有一个名称字段,你可以通过$category->name 获得名称

要获得该类别的文章,你可以做

foreach($category->articles as $article)
// do something with the articles
@endforeach

要获得一个类别的文章数,请执行$category->articles->count();

确保你也阅读过一次Eagle加载的文档,这真的很有帮助。