laravel 相关 table 没有加入的条件在哪里?

laravel where criteria on related table without join?

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

我想在给定时间范围内获取用户的所有 UserChallenges:

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

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

我知道我可以使用连接在一个查询中完成,但我更喜欢使用我在模型中设置的关系的更 eloquent 方式。这有可能吗?

尝试whereHas方法:

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

您还必须在用户模型中定义 belongsToMany 方法。