Laravel 5.3 withCount()嵌套关系

时间:2016-09-22 08:14:12

标签: php eloquent laravel-5.3

模型结构如下

教程 - > (hasMany)章节 - > (hasMany)视频

如何使用laravel 5.3的withCount()方法从教程模型中加载多少个视频(video_count)

我试过了:

Tutorial::withCount('chapters')
->withCount('chapters.videos') // this gives error: Call to undefined method Illuminate\Database\Query\Builder::chapters.videos()
->all();

修改

这可行,任何更好的解决方案?

Tutorial::withCount('chapters')
->with(['chapters' => function($query){
    $query->withCount('videos');
}])
->all();

1 个答案:

答案 0 :(得分:28)

您只能对模型的已定义关系执行withCount()

然而,关系可以是hasManyThrough,这将实现您的目标。

class Tutorial extends Model
{
    function chapters()
    {
        return $this->hasMany('App\Chapter');
    }

    function videos()
    {
        return $this->hasManyThrough('App\Video', 'App\Chapter');
    }
}

然后你可以这样做:

Tutorial::withCount(['chapters', 'videos'])

文档: