分组时如何对父记录和子记录求和?



Message具有属性locationlike_countvote_count

Commentbelongs_to :message,并具有属性like_countvote_count

我已经设法弄清楚如何计算location以及Message在该特定location中获得的票数。

@votes_by_place = Message.where(
:user_id => @user.id).select(
:location).group(:location).sum('like_count + vote_count')
# => "Total votes and likes of your Messages posted in New York, United States ": 192
# => "Total votes and likes of your Messages posted in Paris, France ": 93

我可以保持这样,那就没问题了,但是如果我能找到一种方法来将commentsvote_countlike_countuser_id => @user.id和特定@message.location相加,我真的很喜欢它

这样它就会变成:

# => "Total votes and likes of your Messages and Comments posted in New York, United States ": 192
# => "Total votes and likes of your Messages and Comments posted in Paris, France ": 93

也许如果我location也分配给Comments会更容易?

让我知道您的想法,任何建议将不胜感激!

我不确定如何在单个查询中执行此操作,但是通过两个查询和一点普通的 Ruby 可以完成。也许其他人可以找到更有效的方法。

with_comments = Message.where(user_id: @user.id).
left_outer_joins(:comments).
group(:location).
sum('messages.like_count + messages.vote_count + comments.like_count + comments.vote_count')

第一个查询将messages表和comments表中的所有like_countvote_count添加到具有关联commentsmessages。使用left_outer_joins可确保对group调用为所有消息位置(包括没有关联注释的位置(添加哈希键,以便表示所有用户的消息位置。

without_comments = Message.where(user_id: @user.id).
left_outer_joins(:comments).
where(comments: { message_id: nil }).
group(:location).
sum('messages.like_count + messages.vote_count')

第二个查询仅将messages表中的所有like_countvote_count添加到没有关联commentsmessages

totals = with_comments.dup
totals.each_key do |location|
totals[location] += without_comments[location].to_i
end

dup第一个哈希并迭代它,将两个哈希的值相加并将nil值转换为0

您可以执行此查询。

SELECT location, SUM(comments.vote_count + comments.like_count) as total_vote_and_like FROM messages
JOIN comments ON messages.id = comments.message_id
GROUP BY messages.location

对于活动记录:

@votes_by_place = Message.select("messages.location, SUM(comments.vote_count + comments.like_count) as total_vote_and_like")joins(:comments).where(user_id => @user.id).group("messages.location")

我希望这对你有帮助。

您可以转到此链接以获取详细信息 http://sqlfiddle.com/#!9/65bb32/6。

最新更新