Laravel 5.3 withCount() nested relation

后端 未结 1 1552
感动是毒
感动是毒 2020-12-03 04:59

The model structure is as follows

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

How can we load number of videos (video_count) from Tutorial Model with

相关标签:
1条回答
  • 2020-12-03 05:13

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

    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');
        }
    }
    

    And then you can do:

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

    Docs:

    • https://laravel.com/docs/5.3/eloquent-relationships#has-many-through
    0 讨论(0)
提交回复
热议问题