'integer', ]; public function producto(): BelongsTo { return $this->belongsTo(Producto::class); } public function color(): BelongsTo { return $this->belongsTo(Color::class); } public function size(): BelongsTo { return $this->belongsTo(Size::class); } /** * Relación many-to-many con bodegas */ public function bodegas(): BelongsToMany { return $this->belongsToMany(Bodega::class, 'variante_bodega', 'variante_id', 'bodega_id') ->withPivot('stock') ->withTimestamps(); } /** * Obtener el stock total de la variante en todas las bodegas */ public function getStockTotalBodegas(): int { try { return $this->bodegas()->sum('variante_bodega.stock'); } catch (\Exception $e) { // En caso de error, retornar 0 return 0; } } /** * Obtener el stock efectivo de la variante (considerando bodegas si existen) */ public function getStockEfectivo(): int { try { // Si tiene distribución en bodegas, usar ese stock if ($this->bodegas()->exists()) { return $this->getStockTotalBodegas(); } } catch (\Exception $e) { // En caso de error (tabla no existe, etc.), usar stock directo // Esto puede ocurrir durante migraciones o configuración inicial } // Stock directo de la variante return $this->stock; } }