向嵌套的预加载中添加多个作用域

时间:2018-11-02 18:01:47

标签: laravel eloquent eager-loading

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

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

问题:我仍然从该用户那里得到所有预测(不仅是当前一周的预测)对于我的用户本周创建的预测,将加载正确的匹配项。对于其他预测,没有匹配项,但它们仍被放入我的查询中。

如何向嵌套的急切加载中添加另一个作用域,该作用域将仅选择本周进行的预测或匹配项不为空?(或其他解决方案)

代码:

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

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

1 个答案:

答案 0 :(得分:2)

使用whereHas()

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