95 lines
2.3 KiB
PHP
95 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
|
|
class DetalleCompra extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var array
|
|
*/
|
|
protected $fillable = [
|
|
'compra_id',
|
|
'producto_id',
|
|
'variante_id',
|
|
'bodega_id',
|
|
'cantidad',
|
|
'precio_unitario',
|
|
'subtotal',
|
|
'producto_nombre_snapshot',
|
|
'variante_info_snapshot',
|
|
'DetalleCompra',
|
|
];
|
|
|
|
/**
|
|
* The attributes that should be cast to native types.
|
|
*
|
|
* @var array
|
|
*/
|
|
protected $casts = [
|
|
'id' => 'integer',
|
|
'compra_id' => 'integer',
|
|
'producto_id' => 'integer',
|
|
'variante_id' => 'integer',
|
|
'bodega_id' => 'integer',
|
|
'cantidad'=> 'integer',
|
|
'precio_unitario' => 'decimal:2',
|
|
'subtotal' => 'decimal:2',
|
|
];
|
|
|
|
public function compra(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Compra::class);
|
|
}
|
|
|
|
public function producto(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Producto::class)->withDefault();
|
|
}
|
|
|
|
public function variante():BelongsTo
|
|
{
|
|
return $this->belongsTo(ProductVariant::class)->withDefault();
|
|
}
|
|
|
|
public function bodega(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Bodega::class);
|
|
}
|
|
|
|
/**
|
|
* Obtiene el nombre del producto, usando snapshot si el producto fue eliminado
|
|
*/
|
|
public function getProductoNombreAttribute(): string
|
|
{
|
|
if ($this->producto) {
|
|
return $this->producto->nombre;
|
|
}
|
|
|
|
return $this->producto_nombre_snapshot ?? 'Producto eliminado';
|
|
}
|
|
|
|
/**
|
|
* Obtiene la información de la variante, usando snapshot si la variante fue eliminada
|
|
*/
|
|
public function getVarianteInfoAttribute(): ?string
|
|
{
|
|
if ($this->variante) {
|
|
// Validación defensiva para evitar error "name" on null
|
|
$colorName = $this->variante->color ? $this->variante->color->name : 'Sin color';
|
|
$sizeName = $this->variante->size ? $this->variante->size->name : 'Sin talla';
|
|
|
|
return $colorName . ' / ' . $sizeName;
|
|
}
|
|
|
|
return $this->variante_info_snapshot;
|
|
}
|
|
}
|