slipperydippery
4 months ago

How to find Invoices where the sum of its Payments are less than the Invoice amount

Posted 4 months ago by slipperydippery

I have an Invoice model which has an amount. The Invoice has related Payments, ($invoice->payments), which each also have amounts. I want to run a query to show the Invoices that are not yet fully paid off.

I would like to do this in a single query, because I have thousands of invoices, with possibly tens of payments each.

I know I can get the sum for each Invoice

$invoice->payments
    ->sum(amount)

But I don't know how I can tie this into a global query:

$openInvoices = Invoice::where('amount' < ...);
```

Is this possible with an eloquent query?

Please sign in or create an account to participate in this conversation.