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

krunal05's avatar

how to use withSum on nested relationship Laravel/Eloquent with eager loading?

Let's say for example. I have 3 tables with one-to-many nested relationships

"Topics" => "Questions" => "Answers"

I have "like_count" column in the "Answers" table.

I want to get a total "like_count" for each Topic with eager loading.

somethinglike,

[ [ 'id' => 1, 'topic_name' => "Topic 1", 'total_like_count' => 100 ], [ 'id' => 2, 'topic_name' => "Topic 2", 'total_like_count' => 50 ], [ 'id' => 3, 'topic_name' => "Topic 3", 'total_like_count' => 200 ], ]

using withSum if possible?

0 likes
1 reply
jlrdw's avatar

Make the sum a derived column

Please or to participate in this conversation.