将多个范围添加到嵌套的预加载

adding multiple scopes to nested eager loading

在我的应用程序中,用户可以预测即将举行的足球比赛的比分。

基本上我想显示本周的所有用户预测。为此,我向我的匹配模型添加了一个范围,该范围仅加载本周的匹配项。

问题:我仍然从那个用户那里得到我的所有预测(不仅仅是本周的预测)对于我的用户本周创建的预测,正确的匹配已加载。对于其他预测,没有匹配项,但它们仍然会出现在我的查询中。

如何将另一个范围添加到我的嵌套预加载中,它只会 select 本周做出的预测或匹配不为空?(或其他解决方案)

代码:

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 ▶}
      ]

我的预测数组中有一个关系字段,其中包含正确的匹配项。

使用whereHas():

$user = auth()->user()->load([
    'predictions' => function ($query) {
        $query->whereHas('match', function ($query) {
            $query->thisWeek();
        });
    },
    'predictions.match'
]);