按日期过滤 Elequent 关系

Filter a elequent relationship by date

-- Laravel 8.* --

你好,我正在尝试在 api 中回复有关足球领域的数据。test/api/fixtures/2020-11-06 应该给出一系列联赛以及给定日期的赛程。

此时我 App\Models\League 有一个 fixtures hasMany 过滤器。

/**
 * Get all the fixtures from this league
 */
public function fixtures()
{
    return $this->hasMany('App\Models\Fixture', 'league_id', 'id');
}

在 FixturesController 中,我用 whereHas:

调用它
$leagues = League::with('fixtures')->whereHas('fixtures', function($q) use ($date) { $q->where('date', $date); })->get();


return $this->responseWithSuccess(['leagues' => $leagues ]);

但这是返回错误的答案。

"leagues": [
        {
            "id": 4,
            "...",
            "name": "Premier League",
            "fixtures": [
                {
                    "id": 62,
                    "...",
                    "date": "2020-10-17",

请帮忙! 我究竟做错了什么? 有人能告诉我调试此类错误的最佳方法吗?

whereHas 方法中的相同函数添加到 with 方法中。

按照您的操作方式,whereHas 将过滤在该日期有赛程的联赛,但 with 将为您带来所有赛程每个联赛,而不仅仅是给定日期的联赛。

另一件事,对于日期最好使用 whereDate 而不是 where.

也就是说,您的查询可能如下所示:

League::with(['fixtures' => function($q) use ($date) { 
        $q->whereDate('date', $date); 
    }])
    ->whereHas('fixtures', function($q) use ($date) { 
        $q->whereDate('date', $date); 
    })
    ->get();