You should assign the relationships on your models first. Then you can do something like this:
$location = Location::find($id)
$total = $location->results->sum('score')
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi, hopefully someone can help. I am trying to get some results. I have a Location table and a Results table. A Location can have many Results which contains a filed called score.
Location
Result
I am trying to get the Locations with grouped results as a total so that we can see what the best score is between the locations.
I can do a SQL query on my Result table as follows: SELECT location_id, SUM(score) as total FROM results GROUP BY location_id
However I want to have the Location name so that my results look like:
Any idea what is my best options here? I could get all of the locations and then run queries on them to get the total score but I thought there should be a better / more performant way?
Thanks in advance
@c-andrews do something like Location::withSum('results', 'score')->get();
Please or to participate in this conversation.