Sah*_*ala 21 php eloquent laravel-5.3
模型结构如下
教程 - >(hasMany)章节 - >(hasMany)视频
如何使用laravel 5.3的withCount()方法从Tutorial Model加载视频数量(video_count)
我试过了:
Tutorial::withCount('chapters')
->withCount('chapters.videos') // this gives error: Call to undefined method Illuminate\Database\Query\Builder::chapters.videos()
->all();
Run Code Online (Sandbox Code Playgroud)
编辑
这有效,任何更好的解决方案?
Tutorial::withCount('chapters')
->with(['chapters' => function($query){
$query->withCount('videos');
}])
->all();
Run Code Online (Sandbox Code Playgroud)
tan*_*kay 33
您只能withCount()
对模型的已定义关系执行操作.
然而,一种关系可以hasManyThrough
实现你所追求的目标.
class Tutorial extends Model
{
function chapters()
{
return $this->hasMany('App\Chapter');
}
function videos()
{
return $this->hasManyThrough('App\Video', 'App\Chapter');
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
withCount()
文档: