【问题标题】:Laravel multiple where clause in a whereHas constrain on a hasMany relationshipLaravel 在 whereHas 中的多个 where 子句约束 hasMany 关系
【发布时间】:2021-05-08 15:10:46
【问题描述】:

我有以下疑问...

$pgcs = PrivateGuard::with(['licences', 'state'])
        ->whereHas('licences', function($query){
          $query->whereDate('expiration_of_licence', '<', Carbon::today())
                ->where('renewal', 0);
        })
        ->where('status', 1)
        ->get();

我想获得具有满足上述条件的许可证的 $pgcs,whereDate 可以正常工作,但是 where('renewal', 0) 似乎不能正常工作。 上面的查询得到 $pgcs 的许可证的续订也是 = 1,虽然相同的 $pgc 也有续订值为 0 的许可证和另一个具有 1 的许可证,但我不想要一个具有任何续订价值的许可证的 $pgc 1 要在此查询中检索。我该怎么办?

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    你的情况是

    • [1] pgc .. 拥有两个或多个续订 0 , 1 的许可证
    • [2] pgc .. 有两个或多个续订 0 , 0 的许可证
    • [3] pgc .. 拥有两个或多个续订许可证 1 , 1

    现在您的查询正在获取案例 [1]、[2] 的 pgcs

    所以你必须稍微改变你的查询逻辑,才能得到 [2]

    $pgcs = PrivateGuard::with(['licences', 'state'])
            ->whereHas('licences', function($query){
              $query->whereDate('expiration_of_licence', '<', Carbon::today())
                    ->where('renewal', 0);
            })
            ->whereDoesntHave('licences', function($query){
              $query->where('renewal', 1);
            })
            ->where('status', 1)
            ->get();
    

    【讨论】:

    • 哇!从早上开始,我就一直在这个问题上大发雷霆......谢谢艾哈迈德,它就像魅力一样。
    猜你喜欢
    • 2014-12-13
    • 2016-12-31
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 2023-03-09
    • 2020-10-02
    • 1970-01-01
    相关资源
    最近更新 更多