Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jeliasson's avatar

Automatic join

Hi all,

Imagine I have two models, Invoice and InvoiceLines. Both of them are quite explandatory. (FK invoice_lines.invoice_id = invoice.id). I grab the object using the following:

$invoice = \App\Invoice::get();

Now, Is it possible to, in the model, to extend the response with an custom field called e.g. 'lineTotal' which performs for example:

(SELECT SUM(quantity*price) FROM invoice_lines WHERE invoice_id=$invoice->id)

Bottom line: When I grab an invoice or many invoices, I want to have the invoice_line summorization to it.

What is the best approach? My original thought was to use getAttributeLineTotal - but how would I go ahead and construct that method?

Thanks!

0 likes
4 replies
bobbybouwmann's avatar

I don't know your database structure so this is kinda hard but I think this will help you

You can just use Eloquent to do this

Invoice::select('*', DB::raw('SUM(invoice_lines.quantity * invoice.price) AS lineTotal'))
    ->join('invoice_lines', 'invoice.id', '=', 'invoice_lines.invoice_id')
    ->where('invoice_lines.invoice_id', '=', $invoice->id)
    ->get();
jeliasson's avatar

Sorry for late reply. Apparently my answer did no to thru the first time.

@JarekTkaczyk That was what I was looking for. Thanks!

Please or to participate in this conversation.