Juliatzin
Juliatzin

Reputation: 19695

Eloquent Query with Eager Loading

I want to perform an easy query with Eloquent.

I need to get all open tournament ( tournament->type = 1 ) that are in same country than me. Tournament has no country_id, but I need to do it with

$tournament->owner->country_id == Auth::user()->id

So, In my tournament table, I have a user_id that is the owner, and in my model, I have a working relation that get $tournament->owner

Here is my try ( doesn't work )

openTournaments = App\Tournament::with('owner')
    ->whereHas('owner', function ($query)  {
        $query->where('id', Auth::user()->country_id);
    })
    ->where('type', config('constants.OPEN_TOURNAMENT'))
    ->get();

Any Idea how to fix it???

Upvotes: 0

Views: 56

Answers (1)

Samsquanch
Samsquanch

Reputation: 9146

I'm not sure what your schema looks like, but assuming that the user has a country_id associated with it, and a tournament has an owner associated with it, you should be able to just do this:

openTournaments = App\Tournament::with('owner')
->whereHas('owner', function ($query)  {
    $query->where('country_id', Auth::user()->country_id);
})
->where('type', config('constants.OPEN_TOURNAMENT'))
->get();

Note country_id instead of id.

Upvotes: 1

Related Questions