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

Eloquent多角色用户统计异常:实际2用户却显示3人

问题原因与解决方案

问题原因

你的查询通过join关联了model_has_roles和roles表,其中一名用户同时拥有super_admin和admin两个角色,这会导致该用户在关联后的结果集中生成两条重复记录,加上另一名用户的1条记录,结果集总行数为3。COUNT(*)统计的是结果集的行数,因此得到总用户数3,而非实际的2个用户。

修复方案

将统计总用户数的COUNT(*)改为COUNT(DISTINCT users.id),通过对用户ID去重,得到真实的用户数量。修改后的代码如下:

// Retrieve the counts of admins, users, control operators, and security guards
$countData = User::selectRaw('
    SUM(CASE WHEN roles.name = "admin" THEN 1 ELSE 0 END) as totalAdmins,
    COUNT(DISTINCT users.id) as totalUsers,
    SUM(CASE WHEN roles.name = "control_operator" THEN 1 ELSE 0 END) as totalControl,
    SUM(CASE WHEN roles.name = "security_guard" THEN 1 ELSE 0 END) as totalGuards
')->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
  ->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
  ->first();

如果需要统计拥有super_admin角色的用户数,可在selectRaw中添加对应的SUM语句即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:59:53