2017-10-25 4 views
0
Users UserChallenges(user_id,challenge_id) Challenges(start,end) 

私は与えられた時間範囲内のユーザーのすべてのUserChallengesを取得したい:laravel関連するテーブルの基準はどこにありますか?

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

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

私は私が参加し使用して1つのクエリでそれを行うことができることを知っているが、私が使用して、より説得力のような方法を好むだろう私がモデルに設定した関係。これは何とか可能ですか?あなたはまた、UserモデルにbelongsToMany方法を定義する必要があります

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

+0

あなたが望むものの100%は分かりませんが、関係とWhereHas()メソッドが役立つと思いますhttps://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence –

答えて

2

whereHas方法を試してみてください。

関連する問題