In my application users can predict scores of upcoming soccer games.
Basically I want to display all the user predictions for this week. I do this by adding a scope to my match model that only loads matches from this week.
Problem: I'm still getting all my predictions from that user (not only the ones from the current week) For predictions that my user created this week, the correct match is loaded. For the other predictions there is no match but they still get put in my query.
How can I add another scope to my nested eager loading that will only select predictions made during this week or have a match that is not null? (or other solution)
Code:
public function showPredictions() {
$user = auth()->user()->load(['predictions.match' => function ($query) { $query->thisWeek();}]);
dd($user);
return view('predictions', compact('user'));
}
Match model
public function Predictions() {
return $this->hasMany('App\Prediction', 'match_id', 'match_id');
}
public function scopeThisWeek($query) {
$start_date = now()->previous(Carbon::TUESDAY);
$end_date = now()->next(Carbon::MONDAY);
return $query->whereDate('date','>', $start_date)->whereDate('date','<', $end_date);
}
output
#relations: array:1 [▼
"predictions" => Collection {#265 ▼
#items: array:29 [▼
0 => Prediction {#268 ▶}
1 => Prediction {#269 ▶}
2 => Prediction {#270 ▶}
3 => Prediction {#271 ▶}
4 => Prediction {#272 ▶}
5 => Prediction {#273 ▶}
6 => Prediction {#274 ▶}
7 => Prediction {#275 ▶}
8 => Prediction {#276 ▶}
9 => Prediction {#277 ▶}
10 => Prediction {#278 ▶}
11 => Prediction {#279 ▶}
12 => etc...
]
Output I want to achieve (I have 10 predictions for each user that week)
#relations: array:1 [▼
"predictions" => Collection {#265 ▼
#items: array:10 [▼
0 => Prediction {#268 ▶}
1 => Prediction {#269 ▶}
2 => Prediction {#270 ▶}
3 => Prediction {#271 ▶}
4 => Prediction {#272 ▶}
5 => Prediction {#273 ▶}
6 => Prediction {#274 ▶}
7 => Prediction {#275 ▶}
8 => Prediction {#276 ▶}
9 => Prediction {#277 ▶}
10 => Prediction {#278 ▶}
]
I have a relation field in my predictions array with the correct match in.
Use whereHas()
:
$user = auth()->user()->load([
'predictions' => function ($query) {
$query->whereHas('match', function ($query) {
$query->thisWeek();
});
},
'predictions.match'
]);