Kimmer
261
14
Eloquent

Use SUM of value in related table in where clause

Posted 1 month ago by Kimmer

Hi all,

I'm struggling with what appears to be a difficult query. I'll try to explain as simple as possible.

I have a table called "tracks" and a table called 'votes"

A track can have many votes but a vote can be 1 or -1. These values are stored in a column named "vote" in the "votes" table. So each track has a score from the sum of its votes.

I'm trying to collect tracks below or above a certain score.

So in theory I would need something like this:

Track::with('votes')
->where('sum(votes.vote)','<', 0) // for all tracks with a minus score
->get()

Obviously, this would be too easy.

Is anyone willing and able to nudge me in the right direction?

Thanks!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.