Phyron
Phyron

Reputation: 633

Laravel Sum column of relationship table

I have 2 tables, 'Invoice table', and related 'linesInvoice' table.

To simplify it, I will say that the invoice lines table has only the invoice_id field for the relationship and total for the price.

Now, I need to get last invoices, with his totals (totals, is the sum of column 'total' in every line). I've tried many examples, but none works for me correctly.

Controller:

$lastInvoices = Invoice::latest()
                          ->limit(10)
                          ->with(['invoiceLines'])->get();

Model for relation

public function invoiceLines()
{
    return $this->hasMany(InvoiceLines::class, 'invoice_id');
}

The result that I want for example looks like:

[
  Invoice_id => 1
  total => 500 //Sum of totals in lines of invoice 1
],
[
  Invoice_id => 2
  total => 300 //Sum of totals in lines of invoice 2
],

I guess I could go through all the invoices and lines in foreachs and make the sum. But I hope it can be done in the same query

Upvotes: 0

Views: 1135

Answers (2)

ali hassan
ali hassan

Reputation: 451

Laravel 8^

Invoice::with('invoiceLines')->latest()->first()->invoiceLines()->sum('totle');

totle colme table invoiceLines

Upvotes: 0

ManojKiran
ManojKiran

Reputation: 6341

You can use withSum method. This method accept the relation method as first argument and column to sum as second argument

$lastInvoices = Invoice::latest()
                          ->limit(10)
                          ->withSum('invoiceLines','your_column_name')
                          ->with(['invoiceLines'])->get();

Upvotes: 2

Related Questions