Support the ongoing development of Laravel.io →
Database Eloquent

##Problem I have an eloquent model "Invoice" that hasMany "InvoiceTicket" that belongsTo "Ticket". The Ticket row contains the cost of a ticket. I am trying to write a method in Invoice to get the sum cost of all tickets in an invoice. How do I go down two nested levels to get this?

Thanks in advance for any help, Code examples are much appreciated. Jeff

##Errors SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cost' in 'field list' (SQL: select SUM(cost) AS costs from invoice_ticket)

##Behavior Expected Expecting the sum of all cost fields.

##Actual It is looking in the InvoiceTicket relation when it needs to go to the InvoiceTicket.Ticket relation

##Files https://gist.github.com/hodaddy/8738681

https://gist.github.com/hodaddy/8738701

https://gist.github.com/hodaddy/8738753

Last updated 3 years ago.
0

If you want to select columns from related tables like this you have to join the tables manually - doing with() does not work for this. Also, when selecting from another table you need to add the other table in front of the column, i.e. get(['other_table.column'])

Last updated 3 years ago.
0

anlutro, do mean something like this?

https://gist.github.com/hodaddy/8739373

Last updated 3 years ago.
0

That should work, yes. You can also replace DB::table(..)-> with Model::

Last updated 3 years ago.
0

How would I specify ('invoice AS i') if I switch DB::table(..)-> with Model:: ?

Last updated 3 years ago.
0

hodaddy said:

How would I specify ('invoice AS i') if I switch DB::table(..)-> with Model:: ?

have you try Invoice:: ?

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

hodaddy hodaddy Joined 30 Jan 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.