【问题标题】:Filter a elequent relationship by date按日期过滤 elequent 关系
【发布时间】:2020-11-06 15:40:42
【问题描述】:

-- Laravel 8.* --

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

此时我的 App\Models\League 带有一个过滤器,用于过滤固定装置 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",

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

【问题讨论】:

    标签: laravel eloquent laravel-8


    【解决方案1】:

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

    按照您的操作方式,whereHas 将过滤在该日期有赛程的联赛,但with 将为您提供每个联赛的所有赛程,而不是只是那些在给定日期的人。

    另一件事,对于日期,最好使用whereDate 而不是仅在哪里。

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

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

    【讨论】:

    • 'with' 有第二个参数吗?在我的版本中,它给了我一个错误。
    • 对不起,我的错。您必须将其作为数组 Constraining Eager Loads 传递。我更新了答案
    • 完美的工作就像一个魅力,你能解释为什么当“with”已经在过滤数据时需要“whereHas”吗?还是我弄错了?
    • whereHas 将过滤该日期有赛程的联赛模型(它不会带来没有赛程不符合条件的联赛)。如果你只使用with,它会返回所有的联赛,但是对于那些不符合条件的联赛有一个空的关系字段。
    • 您可以调试您的查询 dumpig it DB Debugging 以查看 DB 级别的差异。
    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2019-03-01
    • 2016-01-10
    • 2018-11-07
    • 1970-01-01
    相关资源
    最近更新 更多