Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 withCount() nested relation

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(); 
like image 631
Sahil Deliwala Avatar asked Sep 22 '16 08:09

Sahil Deliwala


People also ask

What is the has-many-through relationship in Laravel?

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.

How does Laravel determine the relationship name of a 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:

How to count the number of possible polymorphic types in Laravel?

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.

How do I add multiple counts to a relationship in SQL?

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:


1 Answers

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
like image 105
tanerkay Avatar answered Sep 28 '22 02:09

tanerkay