【问题标题】:orderBy sum of related tableorderBy 相关表的总和
【发布时间】:2014-05-18 15:35:43
【问题描述】:

如果我有一个帖子类型 post 有很多 votes 看起来像这样:

post:   [id, title, content]
votes:  [my_vote, post_id, user_id]

my_vote 可以是 -1、0 或 1。

如何列出按 my_vote 总和排序的所有帖子?我可以用雄辩的方式做到这一点,还是我必须用流利的方式使用 JOINS?我想做类似的事情

->orderBy(sum("votes-for-the-idea"))

我还需要访问个人投票(特别是当前用户的投票)。

【问题讨论】:

  • 好问题,我也想知道。

标签: laravel laravel-4


【解决方案1】:
select post.*,
sum(votes.my_vote) as vote_num,
count(distinct votes.user_id) as user_vote_num
from post 
left join votes 
on post.id = votes.post_id 
group by post.id 
order by vote_num desc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多