Chris
Chris

Reputation: 14218

laravel where criteria on related table without join?

Users UserChallenges(user_id,challenge_id) Challenges(start,end)

I want to get all UserChallenges for a user within a given timerange:

$challengeIds = Challenge::where('start', '>=', $timestamp)
            ->where('end', '<=', $timestamp)->pluck('id');

UserChallenge::where('user_id', $userId)->whereIn('id', $challengeIds)->get();

I know that I could do it in one query using joins, but I would prefer a more eloquent like way using the relations that I have setup in the models. Is this somehow possible?

Upvotes: 0

Views: 689

Answers (1)

Laerte
Laerte

Reputation: 7083

Try whereHas method:

$users = User::where('id', $userId)
             ->whereHas('challenges', function ($q) use ($timestamp) {
                 $q->where('start', '>=', $timestamp)
                   ->where('end', '<=', $timestamp);
             })->get();

You will also have to define belongsToMany method in User model.

Upvotes: 3

Related Questions