0

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.

8
  • Please post what you have tried, and where you became stuck. Commented Apr 13, 2018 at 2:05
  • Updated, please check. Commented Apr 13, 2018 at 2:11
  • I don't think you're going to be able to use a whereHas clause, because you need to compare the value from two different tables. Whereas a whereHas just executes a nested sub query. You'll have to use a join instead. Commented Apr 13, 2018 at 2:24
  • And this - My concern is to get the status for the invoice - doesn't make sense. What does it mean? Commented Apr 13, 2018 at 2:24
  • I need to search through all invoices for say like "Paid" status. Commented Apr 13, 2018 at 2:26

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.