fefe
fefe

Reputation: 9055

Laravel conditional subquery with related model last entry

I try to build a query on related model which hasMany relation, where I want to query users with properties where last property has unit_id, group_id or team_id

what I tried but does not works

$users = User::with('properties', function($query) use($catId) {
                $query->where('team_id', $catId)
                    ->orWhere('group_id', $catId)
                    ->orWhere('unit_id', $catId);
            })->get();

this one returns all records

another try

$q = User::with(['properties' =>function($query) use($catId) {

                $query->latest()->where('team_id', $catId)
                    ->orWhere('group_id', $catId)
                    ->orWhere('unit_id', $catId);
            }]);

which returns again all records

Upvotes: 2

Views: 290

Answers (1)

Amarnasan
Amarnasan

Reputation: 15529

Don't use with, use whereHas :

$users = User::whereHas('properties', function($query) use ($catId) {
          $query->where('team_id', $catId)
                ->orWhere('group_id', $catId)
                ->orWhere('unit_id', $catId);
})->get();

Upvotes: 2

Related Questions