You need to enable JavaScript to run this app. Laravel 8中MySQL原生查询转Eloquent并获取分组总计数
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8中MySQL原生查询转Eloquent并获取分组总计数

问题根因

你之前的写法核心逻辑错误:在groupBy分组之后直接执行count(),查询构造器会将聚合函数和分组子句结合,返回的是每组的计数集合,而非你需要的「先按group_id去重分组、再统计分组总个数」的结果。
另外还有两个和原生SQL不匹配的细节:

  • 原生SQL使用INNER JOIN,你误用了leftJoin,虽然受chat_group.is_group = 1的过滤条件影响二者结果差异不大,但逻辑上用join更贴合原生语义
  • 未显式处理chat_histories.deleted_at IS NULL条件(如果ChatHistory模型没有引入Laravel内置SoftDeletes软删除机制,该条件不会自动追加)

正确实现方式

以下三种写法都能直接返回你需要的总条数(即示例中的22这类整数),可根据实际场景选择:

1. 完全对齐原生SQL的子查询写法

和你提供的原生SQL逻辑1:1映射,用fromSub将分组结果作为临时表统计总条数:

// 先构造符合条件的分组子查询
$groupSubQuery = ChatHistory::join('chat_group', 'chat_group.id', '=', 'chat_histories.group_id')
    ->where('chat_group.is_group', 1)
    ->whereBetween('chat_histories.created_at', [$startDate, $endDate])
    // 若ChatHistory未引入软删除,需显式追加该条件
    ->whereNull('chat_histories.deleted_at')
    ->groupBy('chat_histories.group_id')
    ->select('chat_histories.group_id');

// 直接返回统计结果
$totalChatThread = DB::query()->fromSub($groupSubQuery, 'total_chat')->count();

2. 简化的去重计数写法

你需要的本质是「符合条件的不重复group_id的数量」,用countDistinct可以直接实现,性能和子查询写法一致,代码更简洁:

$totalChatThread = ChatHistory::join('chat_group', 'chat_group.id', '=', 'chat_histories.group_id')
    ->where('chat_group.is_group', 1)
    ->whereBetween('chat_histories.created_at', [$startDate, $endDate])
    // 未引入软删除的话追加下面这行
    ->whereNull('chat_histories.deleted_at')
    ->countDistinct('chat_histories.group_id');

3. 基于已定义模型关联的Eloquent写法

不需要手动写join,直接用关联条件实现,代码可读性更高:

$totalChatThread = ChatGroup::where('is_group', 1)
    ->whereHas('chatHistory', function ($query) use ($startDate, $endDate) {
        $query->whereBetween('created_at', [$startDate, $endDate]);
        // 如果ChatHistory引入了软删除,这里会自动追加deleted_at IS NULL的条件,无需手动编写
    })
    ->count();

该写法逻辑为统计所有「是群组、且在指定时间范围内有聊天记录」的群组总数,和业务需求完全匹配。


内容的提问来源于stack exchange,提问作者Md. Ashrafuzzaman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 23:36:03