68 lines
1.6 KiB
PHP
68 lines
1.6 KiB
PHP
<?php
|
||
|
||
namespace App\Models;
|
||
|
||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||
use Illuminate\Database\Eloquent\Model;
|
||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||
use App\Models\ProductVariant;
|
||
|
||
class Bodega extends Model
|
||
{
|
||
use HasFactory;
|
||
|
||
/**
|
||
* The attributes that are mass assignable.
|
||
*
|
||
* @var array
|
||
*/
|
||
protected $fillable = [
|
||
'nombre',
|
||
];
|
||
|
||
/**
|
||
* The attributes that should be cast to native types.
|
||
*
|
||
* @var array
|
||
*/
|
||
protected $casts = [
|
||
'id' => 'integer',
|
||
];
|
||
|
||
/**
|
||
* Relación many‑to‑many con productos.
|
||
*/
|
||
public function productos(): BelongsToMany
|
||
{
|
||
return $this->belongsToMany(Producto::class, 'producto_bodega')
|
||
->withPivot('stock')
|
||
->withTimestamps();
|
||
}
|
||
|
||
/**
|
||
* Relación many-to-many con variantes.
|
||
*/
|
||
public function variantes(): BelongsToMany
|
||
{
|
||
return $this->belongsToMany(ProductVariant::class, 'variante_bodega', 'bodega_id', 'variante_id')
|
||
->withPivot('stock')
|
||
->withTimestamps();
|
||
}
|
||
|
||
/**
|
||
* Obtener el stock total de todos los productos en esta bodega.
|
||
*/
|
||
public function getStockTotalAttribute(): int
|
||
{
|
||
return $this->productos()->sum('producto_bodega.stock');
|
||
}
|
||
|
||
/**
|
||
* Obtener el stock de un producto específico en esta bodega.
|
||
*/
|
||
public function getStockProducto(int $productoId): int
|
||
{
|
||
$producto = $this->productos()->where('producto_id', $productoId)->first();
|
||
return $producto ? $producto->pivot->stock : 0;
|
||
}
|
||
} |