Merge pull request #14308 from snipe/fixes/eager_load_relations_on_locations

Eager load relations to determine deletability on locations
This commit is contained in:
snipe 2024-02-20 22:28:39 +00:00 committed by GitHub
commit ffa7d25fc0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 14 additions and 6 deletions

View file

@ -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) {

View file

@ -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 <snipe@snipe.net>
* @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);
}
/**