db->table('chat_departments') ->select( [ 'chat_departments.id', 'chat_departments.name', 'chat_departments.display', 'chat_department_users.user_id', ] ) ->join( "chat_department_users", "chat_department_users.chat_department_id = chat_departments.id", 'left' ) ->join( "users", "chat_department_users.user_id = users.id", 'left' )->where("chat_departments.type",$type); if(auth()->user()->cliente_id == null){ $query->where("chat_department_users.user_id",auth()->user()->id); } $results = $query->get()->getResultArray(); // Create the desired structure $departments = []; foreach ($results as $row) { $departmentName = $row['name']; // If the department is not yet added to the array, initialize it if (!isset($departments[$departmentName])) { $departments[$departmentName] = [ 'id' => $row['id'], 'name' => $row['name'], 'display' => $row['display'], 'users' => [] // Initialize users as an empty array ]; } // If user_id is not null, add the user to the department's 'users' array if ($row['user_id']) { $departments[$departmentName]['users'][] = $userModel->find($row["user_id"]); } } return $departments; } public function getChatDepartmentUsers(int $chat_deparment_id) { $result = $this->db->table('chat_departments') ->select( [ "users.*" ] ) ->join( "chat_department_users", "chat_department_users.chat_department_id = chat_departments.id", 'left' ) ->join( "users", "chat_department_users.user_id = users.id", 'left' )->where("chat_departments.id",$chat_deparment_id) ->get()->getResultObject(); return $result; } }