簡體   English   中英

如何在Laravel上使用eloquent執行多表select

[英]How to perform a multi table select using eloquent on Laravel

我有以下情況:

1 - 一張發票可以有很多項目(商品或服務),每件商品或服務都以自己的價格出售。 (發票項目表)。 在這種情況下,如果我們想知道發票的總金額,我們可以將與之相關的項目的金額相加。

2 - 一張發票可以通過多張收據支付。 因此,如果我們想知道發票是否已全額支付,我們將對每個 receipt_item 支付的金額求和。

有關場景的更多詳細信息,請查看所附圖表。

我想要兩個 eloquent 查詢或其他東西,可以幫助我: 賴

  1. 檢索所有未支付的發票。
  2. 通過查詢檢查單張發票是否已支付。

請考慮在我的發票 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM