2016-09-22 139 views
9

该模型结构如下Laravel 5.3 withCount()嵌套关系

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

我们怎样才能加载的从教程模型视频(VIDEO_COUNT)数与laravel 5.3的withCount()方法

我曾尝试:

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(); 
+0

有你定义模型的关系? –

+0

你只需要做一个 - > withCount('chapters.videos')。另外,确保您的关系设置正确。 – 2016-09-22 15:22:24

+0

@DigitalFire关系是正确的,因为我可以加载他们急切的加载。只是计数不会与withCount()方法填充 – crazy1337

回答

14

您只能在模型的定义关系上执行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'])

文档:

+0

非常感谢你!我不认为这样更容易。 – july77

+0

感谢您的回应。绝对帮助我提高了表现。 –