【问题标题】:Laravel whereHas check last latest record for condition in nested relationLaravel whereHas 检查嵌套关系中的最后一条最新记录
【发布时间】:2022-01-03 03:28:33
【问题描述】:

我需要检查whereHas 中最新的最后一条记录是否有type 等于1。

$model->users()
    ->whereHas('relation', function ($query) use ($dates) {
        $query->whereBetween('created_at', $dates)
              ->latest()
              -> .... 
    });

已编辑

【问题讨论】:

    标签: laravel laravel-8 query-builder laravel-query-builder


    【解决方案1】:

    如果 最新 你的意思是 updated_at 时间戳是最新的,那么你可以做类似的事情

    ->whereHas('relation', function ($query) {
       $query->latest() // orderByDesc('updated_at')
             ->limit(1)
             ->where('type', 1);
    })
    

    【讨论】:

    • 好的,所以我可能应该补充一点,它就像二级关系,因为我收到此错误:“SQLSTATE [42000]:语法错误或访问冲突:1140 GROUP 列混合(MIN()如果没有 GROUP BY 子句,则没有 GROUP 列的 ,MAX(),COUNT(),...) 是非法的”。我正在这样做: $department->users()->whereHas('applications', {....}) and users() is belongsToMany and applications is hasMany
    • 您在查询中是否使用了 count()、min()、max() 等聚合函数?
    • 整个查询:$department->users() ->whereHas('applications', function ($query) use ($dates) { $query->whereBetween('created_at', $dates) ->latest() ->limit(1) ->where('type', 1); }, '>=', 2) ->with([ 'applications' => function ($query) use ($dates ) { return $query->whereBetween('created_at', $dates); } ]) ->get();
    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多