![](/img/trans.png)
[英]How to use Multi table queries in Laravel without using Eloquent Relationships
[英]How to perform a multi table select using eloquent on Laravel
我有以下情況:
1 - 一張發票可以有很多項目(商品或服務),每件商品或服務都以自己的價格出售。 (發票項目表)。 在這種情況下,如果我們想知道發票的總金額,我們可以將與之相關的項目的金額相加。
2 - 一張發票可以通過多張收據支付。 因此,如果我們想知道發票是否已全額支付,我們將對每個 receipt_item 支付的金額求和。
有關場景的更多詳細信息,請查看所附圖表。
請考慮在我的發票 Model 中我有:
public function invoiceItems()
{
return $this->hasMany(InvoiceItem::class, 'invoices_id');
}
public function payments()
{
return $this->hasMany(Payment::class, 'invoices_id');
}
您可以將 append 屬性添加到您的發票 model,例如:
$appends = ['is_paid'];
此屬性需要一個訪問器(閱讀有關訪問器的文檔):
public function getIsPaidAttribute () {
// here you can make the calculation and return a true/false value
}
現在,在您的 controller 中,您可以獲取發票並使用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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.