You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Eloquent关联查询按天分组报错的解决方法咨询

问题原因解析

问题1报错原因

Eloquent查询构造器的groupBy方法仅支持传入数据库字段名或合法SQL表达式,闭包是Laravel集合类的groupBy方法才支持的用法,所以在QueryBuilder阶段传入闭包参数会触发参数类型错误。

问题2报错原因

rawrates是一对多关联属性,调用$date->rawrates返回的是多个RawRate模型组成的集合实例,不是单个模型对象,直接访问created_at属性自然不存在。


解决方案

方案1:每个费率描述下的关联费率单独按天分组

适合需要保留费率描述层级、每个费率描述下的费率单独分组的场景:

$ratesbydate = RateDescription::where('company_id', 7)
    // 过滤出存在近7天费率数据的费率描述
    ->whereHas('rawrates', function ($query) use ($sub7days) {
        $query->where('created_at', '>=', $sub7days);
    })
    // 预加载符合条件的费率数据,同时按创建时间倒序
    ->with(['rawrates' => function ($query) use ($sub7days) {
        $query->where('created_at', '>=', $sub7days)->orderByDesc('created_at');
    }])
    ->get()
    // 对每个费率描述下的费率集合按天分组
    ->map(function ($rateDesc) {
        $rateDesc->rawrates = $rateDesc->rawrates->groupBy(function ($rawRate) {
            // Laravel默认created_at已是Carbon实例,无需额外解析
            return $rawRate->created_at->format('d');
        });
        return $rateDesc;
    });

方案2:所有符合条件的费率统一按天分组

适合不需要保留费率描述层级、直接按天归类所有费率的场景,直接从费率模型查询更高效:

$ratesbydate = RawRate::with('rateDescription')
    ->where('created_at', '>=', $sub7days)
    ->whereHas('rateDescription', function ($query) {
        $query->where('company_id', 7);
    })
    ->orderByDesc('created_at')
    ->get()
    ->groupBy(function ($rawRate) {
        return $rawRate->created_at->format('d');
    });

内容的提问来源于stack exchange,提问作者peter88uk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:36:04