Laravel中如何实现相同键合并,Laravel8统计相同国家游客数量
错误原因
你的查询存在两个核心问题,导致同国家数据没有合并:
groupBy('country_id', 'count')同时按国家ID、到访人数两个字段分组,只要同一国家的count值不同,就会被拆分为独立分组,自然无法合并统计。- 你需要的是同国家的访客总数,应该用聚合函数
sum()累加count字段,而非用group_concat()拼接字段值。
修正方案
方案1:直接通过SQL查询合并统计(推荐)
仅按country_id分组,用sum统计总访客数,查询代码如下:
return view('stats.counter', [ 'stats' => Stat::groupBy('country_id') ->selectRaw('country_id, sum(count) as total_visitors') ->whereDate('created_at', Carbon::today()) ->get() ]);
如果需要同时返回国家名称,可关联countries表查询(前提是Stat模型已经定义了country关联方法,关联Country模型):
return view('stats.counter', [ 'stats' => Stat::with('country') ->groupBy('country_id') ->selectRaw('country_id, sum(count) as total_visitors') ->whereDate('created_at', Carbon::today()) ->get() // 可选:格式化返回国家名+访客数的结构 ->map(fn($item) => [ 'country_name' => $item->country->name, 'total_visitors' => $item->total_visitors ]) ]);
方案2:通过Laravel集合手动合并
如果已经拿到全量原始数据,也可以用集合的内置方法实现合并:
// 先拿到当日所有原始记录 $rawStats = Stat::whereDate('created_at', Carbon::today())->get(); // 按country_id分组后累加每组的count值 $mergedStats = $rawStats->groupBy('country_id')->map(fn($group) => $group->sum('count'));
内容的提问来源于stack exchange,提问作者lasshak
相关产品推荐
相关产品推荐

