Files
star-erp/app/Models/PurchaseOrderItem.php

69 lines
1.6 KiB
PHP
Raw Normal View History

2025-12-30 15:03:19 +08:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class PurchaseOrderItem extends Model
{
use HasFactory;
protected $fillable = [
'purchase_order_id',
'product_id',
'quantity',
2026-01-08 16:32:10 +08:00
'unit_id', // 新增單位ID欄位
2025-12-30 15:03:19 +08:00
'unit_price',
'subtotal',
'received_quantity',
];
protected $casts = [
'quantity' => 'decimal:2',
'unit_price' => 'decimal:2',
'subtotal' => 'decimal:2',
'received_quantity' => 'decimal:2',
];
public function getProductNameAttribute(): string
{
return $this->product?->name ?? '';
2025-12-30 15:03:19 +08:00
}
2026-01-08 16:32:10 +08:00
// 關聯單位
public function unit(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Unit::class);
}
2025-12-30 15:03:19 +08:00
2026-01-08 16:32:10 +08:00
public function getUnitNameAttribute(): string
2025-12-30 15:03:19 +08:00
{
2026-01-08 16:32:10 +08:00
// 優先使用關聯的 unit
if ($this->unit) {
return $this->unit->name;
}
if (!$this->product) {
return '';
}
2026-01-08 16:32:10 +08:00
// Fallback: 嘗試從 Product 的關聯單位獲取
return $this->product->purchaseUnit?->name
?? $this->product->largeUnit?->name
?? $this->product->baseUnit?->name
?? '';
2025-12-30 15:03:19 +08:00
}
public function purchaseOrder(): BelongsTo
{
return $this->belongsTo(PurchaseOrder::class);
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}