我有以下情况:
1-一张发票可以包含许多物品(商品或服务),每种商品或服务都以自己的价格出售。 (Invoice_items表)。在这种情况下,如果我们想知道发票的总金额,则可以对与之关联的项目的总金额进行求和。
2-可以通过许多收据来支付发票。因此,如果我们想知道发票是否已全部支付,我们将在每个receipment_item上支付的金额相加。
有关该场景的更多详细信息,请查看附图。
请考虑在我的发票模型中,我有:
public function invoiceItems()
{
return $this->hasMany(InvoiceItem::class, 'invoices_id');
}
public function payments()
{
return $this->hasMany(Payment::class, 'invoices_id');
}
答案 0 :(得分:0)
您可以append an attribute进入发票模型,例如:
$appends = ['is_paid'];
此属性需要访问器(请阅读有关访问器的文档):
public function getIsPaidAttribute () {
// here you can make the calculation and return a true/false value
}
现在,在您的控制器中,您可以使用invoice.is_paid
属性获取发票并进行过滤。
// retrieve all invoices
// you might need to add where conditions to lighten up
// the results if you have thousands of records
$invoices = Invoice::all();
// filter paid invoices
$paidInvoices = $invoices->filter(function($i){
return $i->is_paid === true;
});
最后,如果您想知道是否已支付发票,只需索要$invoice->is_paid
。