Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager loading with conditional - Laravel

I have this query:

 $tournament = Tournament::with(
            'championships',
            'championships.settings',
            'championships.category',
            'championships.tree.users',
        )->first();

Right now, it gives me the tournament with all attached championships.

What I need is to get the tournament but only with the championship which match the $request->championshipId that I have.

Off course, I also want this filter in all the other relations ('championships.settings', 'championships.category','championships.tree.users')

like image 800
Juliatzin Avatar asked Nov 10 '16 17:11

Juliatzin


2 Answers

You can use Constraining Eager Loading like this:

$tournaments = Tournament::with(['championships' => function ($query) {
    $query->where('something', 'like', '%this%');
},
'championships.settings' => function ($query) {
    $query->where('something', 'like', '%this%');
},
...])->get();
like image 170
Saumya Rastogi Avatar answered Oct 10 '22 12:10

Saumya Rastogi


Load the relations in the subquery constraint:

$tournament = Tournament::with(['championships' => function($query) use ($request) {
    return $query->where('id', $request->championshipId)
        ->with([
            'settings',
            'category',
            'tree.users'
        ]);
}])->first();
like image 27
Eric Tucker Avatar answered Oct 10 '22 12:10

Eric Tucker