admin管理员组文章数量:1289497
I have this query:
$invoices = Vendor_invoice::where('vendor_id',$id)->where('status','!=',"Paid")->orderBy('due_date', "ASC")->get();
It gets all invoices that are not paid in full for a specific vendor. It's possible that payments have been applied to an invoice so I need to query the Invoice_payments table to get the sum of all payments applied to an invoice and do so within the same query in order to populate a table and include the amount due and not simply the invoice total.
I have this query:
$invoices = Vendor_invoice::where('vendor_id',$id)->where('status','!=',"Paid")->orderBy('due_date', "ASC")->get();
It gets all invoices that are not paid in full for a specific vendor. It's possible that payments have been applied to an invoice so I need to query the Invoice_payments table to get the sum of all payments applied to an invoice and do so within the same query in order to populate a table and include the amount due and not simply the invoice total.
Share Improve this question asked Feb 19 at 23:52 T.A.T.A. 6421 gold badge7 silver badges17 bronze badges 1 |2 Answers
Reset to default 1you can use addSelect
$invoices = Vendor_invoice::addSelect([
'amount_due' => Invoice_payments::selectRaw('sum(amount)')->whereColumn('num_invoice', 'Vendor_invoice.id')
])->where('vendor_id',$id)->where('status','!=',"Paid")->orderBy('due_date', "ASC")->get();
Since I do not know the entire table structure, I might be using a different FK, but here's a query that might help you.
$invoices = Vendor_invoice::where('vendor_id',$id)
->withSum('invoicePayments', 'price')
->where('status','!=',"Paid")
->orderBy('due_date', "ASC")
->get();
This assumes that your Vendor_invoice
model implements the eloquent relation of Invoice_Payment
model, and the sum of price
column of invoice_payments table.
After applying the withSum
query, you can access its value like this:
$invoices[0]->invoicePayments_sum_price
This can be found in Laravel's documentation.
Hopefully this helps.
本文标签: Laravel Query with FunctionStack Overflow
版权声明:本文标题:Laravel Query with Function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741465023a2380262.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
withSum
Method to get the sum – ManojKiran Commented Feb 20 at 7:01