简体   繁体   中英

Laravel query for multiple relationships

I have a required to calculate the invoices status - Open, Paid, Overdue.

My table structure:

invoices:
- id
- custome_id
- total_amount
...

invoice_payments
- id
- invoice_id
- amount_received
...

Trying:

$records->whereHas('invoice', function($query) use ($val) {
    $query->whereHas('invoicePayments', function($_query){
        $_query->sum('amount_received');
    });
});

My concern is to get the status for the invoice - if invoice->sum('amount') > invoice->invoicePayment->sum('amount_received') .

I want to do it with the help of whereHas functions not with database raw queries. Please suggest the way to do it.

This query works with pagination:

Invoice::where('total_amount', '<=', function($query) {
    $query->selectRaw('SUM(amount_received)')
        ->from('invoice_payments')
        ->where('invoice_id', DB::raw('invoices.id'));
})->paginate();

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