![[Laravel]リレーション先テーブルにデータが存在するものだけを取得する方法](https://www.yukiiworks.com/wp-content/uploads/2019/05/laravel.png)
はじめに
Laravelでリレーション先に紐づくデータが存在するものだけを取得したい時ってありませんか?
例えば学生を保存するテーブルと所属する部活を保存しているテーブルがあったとします。
このときに、何らかの部活に所属している学生だけを取得したい!
そんなときです。似たようなケースがあったのでその時の解決方法をメモします。
例
以下のような学生テーブルのモデルと部活所属テーブルのモデルがあるとします。
1 2 3 4 5 6 7 8  | class Student extends Model {     // 学生と所属する部活の関係     public function club()     {         return $this->hasMany('App\Eloquent\BelongsClub');     } }  | 
1 2 3 4 5 6 7  | class BelongsClub extends Model {     public function belongsStudent()     {         return $this->belongsTo('App\Eloquent\Student');     } }  | 
これは学生と部活が1対多であることを示しています。
このような場合に部活に所属している学生だけを取得します。
方法
以下のようにwhereHasとwhereExistsを組み合わせることで取得できます。
1 2 3 4 5 6  | Student::with('club')     ->whereHas('club', function ($query) {         $query->whereExists(function ($query) {             return $query;         })     ->get();  | 
withの引数はリレーション先を指定しているStudentクラスのメソッド名です。
whereExistsでリレーション先が存在するものだけに絞り込んでいます。
以上です。
![[Laravel]datetime型の項目を年・月・日・日付・時刻で検索する方法](https://www.yukiiworks.com/wp-content/uploads/2019/05/laravel-300x209.png)
![[Android][Kotlin]ToolBarのタイトルを消す方法](https://www.yukiiworks.com/wp-content/uploads/2019/10/android-studio-e1585186990750-150x150.jpg)
![[Laravel]Formの配列をバリデーションでチェックする方法](https://www.yukiiworks.com/wp-content/uploads/2019/05/laravel-150x150.png)
![[Kotlin][Android]BottomNavigationViewとViewPagerを用いたタブ遷移の実装](https://www.yukiiworks.com/wp-content/uploads/2019/04/kotlin-150x150.png)

![[Node.js]AWS Lambda上で日本現在時刻を取得する](https://www.yukiiworks.com/wp-content/uploads/2020/04/lambda30-150x150.png)
![[Xcode]error: unable to parse contents of file list ‘<project path>/Pods/Target Support Files/Pods-XXX/Pods-XXX-frameworks-Debug-input-files.xcfilelist’でビルドエラーの解消方法](https://www.yukiiworks.com/wp-content/uploads/2019/09/Xcode-150x150.png)
