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

Laravel实现查询结果按created_date、affiliate_ad多维分组

解决Laravel查询结果按日期合并分组的问题

你已经完成了数据库层面的分组统计逻辑,现在只需要在Laravel Collection层面做一次二次分组,就能把相同c_date的记录合并到同一个数组元素里。

解决方案

在现有查询代码的基础上,链式调用Collection的groupBy()和values()方法即可实现需求:

return DB::table($this->table) 
    ->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : []) 
    ->select('id', 'created_date','affiliate_ad', DB::raw('count(*) as total,count(affiliate_ad=1) as affiliate_ad_count,SUBSTRING(`created_date`, 1, 10) AS c_date')) 
    ->groupBy('affiliate_ad','c_date') 
    ->orderBy('c_date', 'desc') 
    ->get()
    // 按c_date字段分组,将同日期的记录归为一组
    ->groupBy('c_date')
    // 移除分组的日期键,转为连续索引的数组结构
    ->values();

代码说明

  1. groupBy('c_date'):这一步会把查询返回的扁平Collection,按照c_date字段重新分组。分组后,Collection的键是日期字符串(比如"2018-01-10"),对应的值是该日期下所有affiliate_ad分组的记录数组。
  2. values():由于groupBy()会保留日期作为键,而你期望的结果是纯索引数组,所以用这个方法把键重置为0、1、2...的连续数字索引,完全匹配你想要的结构。

结果验证

经过上述处理后,返回结果会变成你期望的结构:

Collection {#385 #items: array:2 [
  0 => [
    0 => {#386 +"id": 354766 +"created_date": "2018-01-10 10:16:27" +"affiliate_ad": 1 +"total": 2 +"affiliate_ad_count": 1 +"c_date": "2018-01-10" },
    1 => {#384 +"id": 354730 +"created_date": "2018-01-10 10:10:39" +"affiliate_ad": 0 +"total": 3 +"affiliate_ad_count": 4 +"c_date": "2018-01-10" }
  ],
  1 => [
    0 => {#387 +"id": 338263 +"created_date": "2018-01-08 10:10:52" +"affiliate_ad": 0 +"total": 83 +"affiliate_ad_count": 83 +"c_date": "2018-01-08" }
  ]
]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:09:00