belongsToMany(Recipe::class, 'recipes_spices') ->withPivot('amount_in_percent') ->withTimestamps(); } public function stockMovements() { return $this->hasMany(SpiceStockMovement::class); } public function recalculateQuantity(): void { $this->update(['quantity' => $this->stockMovements()->sum('amount')]); } public function recalculatePieceWeight(): void { $result = SpiceSupplier::where('spice_id', $this->id) ->whereNotNull('weight_g') ->where('weight_g', '>', 0) ->selectRaw('SUM(weight_g) as total_grams, SUM(amount) as total_pieces') ->first(); if ($result && $result->total_pieces > 0) { $this->update(['piece_weight' => round($result->total_grams / $result->total_pieces, 3)]); } } }