diff --git a/app/Models/Component.php b/app/Models/Component.php index 7493d204c4..445a2cc530 100644 --- a/app/Models/Component.php +++ b/app/Models/Component.php @@ -110,6 +110,18 @@ class Component extends SnipeModel 'manufacturer' => ['name'], ]; + public static function booted() + { + static::saving(function ($model) { + // We use 'sum_unconstrained_assets' as a 'cache' of the count of the sum of unconstrained assets, but + // Eloquent will gladly try to save the value of that attribute in the case where we populate it ourselves. + // But when it gets populated by 'withSum()' - it seems to work fine due to some Eloquent magic I am not + // aware of. During a save, the quantity may have changed or other aspects may have changed, so + // "invalidating the 'cache'" seems like a fair choice here. + unset($model->sum_unconstrained_assets); + }); + } + public function isDeletable() { @@ -255,6 +267,8 @@ class Component extends SnipeModel if (is_null($this->sum_unconstrained_assets) || $recalculate) { // This, in a components-listing context, is mostly important for when it sets a 'zero' which // is *not* null - so we don't have to keep recalculating for un-checked-out components + // NOTE: doing this will add a 'pseudo-attribute' to the component in question, so we need to _remove_ this + // before we save - so that gets handled in the 'saving' callback defined in the 'booted' method, above. $this->sum_unconstrained_assets = $this->uncontrainedAssets()->sum('assigned_qty') ?? 0; } return $this->sum_unconstrained_assets;