首頁  >  問答  >  主體

使用 Eloquent 查詢將使用者分組(總使用者、管理員使用者、控制操作員、警衛)

我有一個查詢,其中計算所有用戶具有角色「admin」的用戶總數具有角色「control_operator」的用戶總數和具有角色「guard」的使用者總數。

查詢正在工作,但有一個我無法弄清楚的小故障/錯誤。

資料庫中實際上有 2 個用戶,其中一個具有 super_admin 和 admin 角色,另一個具有 control_operator。前端顯示的是這樣的:

為什麼只有 2 個使用者時卻有 3 個使用者?

這是我的查詢

// 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(*) 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();

P粉026665919P粉026665919196 天前384

全部回覆(1)我來回復

  • P粉111227898

    P粉1112278982024-04-06 10:47:29

    雷雷

    回覆
    0
  • 取消回覆