The model structure is as follows
Tutorial -> (hasMany) Chapters -> (hasMany) videos
How can we load number of videos (video_count) from Tutorial Model with laravel 5.3's withCount() method
I have tried:
Tutorial::withCount('chapters') ->withCount('chapters.videos') // this gives error: Call to undefined method Illuminate\Database\Query\Builder::chapters.videos() ->all();
Edit
This works, Any Better solution?
Tutorial::withCount('chapters') ->with(['chapters' => function($query){ $query->withCount('videos'); }]) ->all();
The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform like Laravel Vapor. A Project model might access many Deployment models through an intermediate Environment model.
By default, Laravel will determine the relationship associated with the given model based on the class name of the model; however, you may specify the relationship name manually by providing it as the second argument to the whereBelongsTo method:
This will instruct Laravel to retrieve all of the possible polymorphic types from the database. Laravel will execute an additional query in order to perform this operation: Sometimes you may want to count the number of related models for a given relationship without actually loading the models. To accomplish this, you may use the withCount method.
By passing an array to the withCount method, you may add the "counts" for multiple relations as well as add additional constraints to the queries: You may also alias the relationship count result, allowing multiple counts on the same relationship:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With