Juliatzin
Juliatzin

Reputation: 19695

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

Upvotes: 22

Views: 32256

Answers (3)

sh6210
sh6210

Reputation: 4540

There is another way of doing this, first grab data.

$user = User::all();

then add the condition to load relation

if(condition){

     $user->load('profile')
}

Or you can use WHEN to conditionally load the relational data.

$doctors = new Doctor();

    $doctors->with( 'subSpeciality' )
            ->when( $searchKey, function ( $query ) use ( $searchKey ) {
               return $query->where( 'name', 'like', "%$searchKey%" )
                            ->orwhere( 'code', 'like', "%$searchKey%" )
                            ->orwhere( 'sfdc_code','like',"%$searchKey%" );
            } );

Upvotes: 1

Saumya Rastogi
Saumya Rastogi

Reputation: 13693

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();

Upvotes: 53

Eric Tucker
Eric Tucker

Reputation: 6335

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();

Upvotes: 11

Related Questions