简体   繁体   中英

How to perform a multi table select using eloquent on Laravel

I have the following scenario:

1 - One invoice can have many items (goods or services), each good or service is sold with its own price. (Invoice_items table). In this case if we want to know the total amount of an invoice we kind of sum the amount of the items associated with it.

2 - An invoice can be paid via many receipts. So if we want to know if an invoice is totally paid we sum the amount paid on each receipt_item.

For more details about the scenario check the attached diagram.

I want two eloquent queries or something, that can help me to: 赖

  1. retrieve all invoices that are not paid.
  2. Check from a query if a single invoice is paid or not.

Please consider that in my Invoice Model I have:


public function invoiceItems()
    {
        return $this->hasMany(InvoiceItem::class, 'invoices_id');
    }


 public function payments()
    {
        return $this->hasMany(Payment::class, 'invoices_id');
    }

You may append an attribute to your invoice model, for example:

$appends = ['is_paid'];

This property needs an accessor (read the docs about accessors):

public function getIsPaidAttribute () {
    // here you can make the calculation and return a true/false value
}

Now, in your controller, you can get your invoices and filter using the invoice.is_paid attribute.

// 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;
});

And finally, if you want to know if an invoice is paid just ask for $invoice->is_paid .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM