>  Q&A  >  본문

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일 전381

모든 응답(1)나는 대답할 것이다

  • P粉111227898

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

    으아악

    회신하다
    0
  • 취소회신하다