diff --git a/app/Http/Controllers/Table/LocationController.php b/app/Http/Controllers/Table/LocationController.php index 50b720179a54..a8e2a925b8c5 100644 --- a/app/Http/Controllers/Table/LocationController.php +++ b/app/Http/Controllers/Table/LocationController.php @@ -44,7 +44,11 @@ public function searchFields($request) protected function sortFields($request) { - return ['location', 'devices', 'down']; + return [ + 'location', + 'devices' => 'devices_count', + 'down' => 'down_count', + ]; } /** @@ -55,19 +59,10 @@ protected function sortFields($request) */ public function baseQuery($request) { - // joins are needed for device count sorts - $sort = $request->get('sort'); - $key = key($sort); - $join = $this->getJoinQuery($key); - - if ($join) { - return Location::hasAccess($request->user()) - ->select(['id', 'location', 'lat', 'lng', \DB::raw("COUNT(device_id) AS `$key`")]) - ->leftJoin('devices', $join) - ->groupBy(['id', 'location', 'lat', 'lng']); - } - - return Location::hasAccess($request->user()); + return Location::hasAccess($request->user())->withCount([ + 'devices', + 'devices as down_count' => fn ($q) => (new Device)->scopeIsDown($q), + ]); } /** @@ -81,22 +76,8 @@ public function formatItem($location) 'location' => htmlspecialchars((string) $location->location), 'lat' => $location->lat, 'lng' => $location->lng, - 'down' => $location->devices()->isDown()->count(), - 'devices' => $location->devices()->count(), + 'devices' => $location->devices_count, + 'down' => $location->down_count, ]; } - - private function getJoinQuery($field) - { - return match ($field) { - 'devices' => function ($query): void { - $query->on('devices.location_id', 'locations.id'); - }, - 'down' => function ($query): void { - $query->on('devices.location_id', 'locations.id'); - (new Device)->scopeIsDown($query); - }, - default => null, - }; - } }