Skip to content

A free open source IT asset/license management system

Eager load relations to determine

snipe04891c7c6126
diff --git a/app/Http/Controllers/LocationsController.php b/app/Http/Controllers/LocationsController.php
index dad1d0b241..7a3691684f 100755
--- a/app/Http/Controllers/LocationsController.php
+++ b/app/Http/Controllers/LocationsController.php
@@ -289,7 +289,12 @@ class LocationsController extends Controller
// Make sure some IDs have been selected
if ((is_array($locations_raw_array)) && (count($locations_raw_array) > 0)) {
- $locations = Location::whereIn('id', $locations_raw_array)->get();
+ $locations = Location::whereIn('id', $locations_raw_array)
+ ->withCount('assignedAssets as assigned_assets_count')
+ ->withCount('assets as assets_count')
+ ->withCount('rtd_assets as rtd_assets_count')
+ ->withCount('children as children_count')
+ ->withCount('users as users_count')->get();
$valid_count = 0;
foreach ($locations as $location) {
diff --git a/app/Models/Location.php b/app/Models/Location.php
index 1122b5da15..2965ff2fc0 100755
--- a/app/Models/Location.php
+++ b/app/Models/Location.php
@@ -95,7 +95,10 @@ class Location extends SnipeModel
/**
- * Determine whether or not this location can be deleted
+ * Determine whether or not this location can be deleted.
+ *
+ * This method requires the eager loading of the relationships in order to determine whether
+ * it can be deleted. It's tempting to load those here, but that increases the query load considerably.
*
* @author A. Gianotto <[email protected]>
* @since [v3.0]
@@ -104,10 +107,10 @@ class Location extends SnipeModel
public function isDeletable()
{
return Gate::allows('delete', $this)
- && ($this->assignedAssets()->count() === 0)
- && ($this->assets()->count() === 0)
- && ($this->children()->count() === 0)
- && ($this->users()->count() === 0);
+ && ($this->assets_count === 0)
+ && ($this->assigned_assets_count === 0)
+ && ($this->children_count === 0)
+ && ($this->users_count === 0);
}
/**