5 months ago

Where constraints on children in nested eager loading

Posted 5 months ago by RainDeer

I have 3 models:

  • User
  • Track
  • Genre


User many-to-many with Track

Track many-to-many with Genre

I'm trying to eager load as below

$user = Auth::user();
$tracks = User::with(['tracks' => function($q){
            $q->where('release_date', 'like', '2011%')->wherePivot('rating', '>=', '3' );
        },'tracks.genres' => function($q){
            $q->where('genre', '=', 'Hip Hop');

This gives me all tracks released 2011 with rating >= as expected but not only tracks with genre = Hip Hop but all tracks. However tracks with another genre are not populated with their genre in the result.

I could loop through the results to only get the ones with genre = Hip Hop but rather exclude them in the query.

How do I go about?

Please sign in or create an account to participate in this conversation.