本文介绍了Laravel 5.3 withCount()嵌套关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型结构如下

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

Tutorial -> (hasMany) Chapters -> (hasMany) videos

如何使用laravel 5.3的withCount()方法来加载教程模型中的视频数量(video_count)

How can we load number of videos (video_count) from Tutorial Model with laravel 5.3's withCount() method

我尝试过:

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

修改

这个工作,任何更好的解决方案?

This works, Any Better solution?

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


推荐答案

你只能做一个 withCount()在模型的定义关系上。

You can only do a withCount() on a defined relation of the model.

然而,关系可以是 hasManyThrough 这将实现你以后的任务。

However, a relationship can be hasManyThrough which would achieve what you are after.

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

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

然后你可以做:

教程:: withCount(['章节','视频'])

文件:



  • https://laravel.com/docs/5.3/eloquent-relationships#has-many-through

这篇关于Laravel 5.3 withCount()嵌套关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 20:59