【发布时间】:2019-04-07 00:01:33
【问题描述】:
在我的应用程序中,用户可以预测即将到来的足球比赛的比分。
基本上我想显示本周的所有用户预测。为此,我向我的匹配模型添加了一个范围,该范围仅加载本周的匹配项。
问题:我仍然从该用户那里获得所有预测(不仅是本周的预测)对于我的用户本周创建的预测,加载了正确的匹配。对于其他预测,没有匹配项,但它们仍会出现在我的查询中。
如何将另一个范围添加到我的嵌套预加载中,该范围将仅选择本周做出的预测或匹配不为空的?(或其他解决方案)
代码:
public function showPredictions() {
$user = auth()->user()->load(['predictions.match' => function ($query) { $query->thisWeek();}]);
dd($user);
return view('predictions', compact('user'));
}
匹配模型
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);
}
输出
#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...
]
我想要实现的输出(我对每个用户那周有 10 个预测)
#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 ▶}
]
我的预测数组中有一个关系字段,其中包含正确的匹配项。
【问题讨论】:
标签: laravel eloquent eager-loading