我需要创建一个包含下表数据的查询:
*Conversation:一种在用户之间对消息进行分组的模型
class Conversation < ActiveRecord::Base
# Associations
has_many :messages, dependent: :destroy
has_many :conversation_participants
has_many :users, :through => :conversation_participants
## Attributes title, created_at, updated_at
end
* ConversationParticipant:一个跟踪对话用户的模型
class ConversationParticipant < ActiveRecord::Base
## Associations
belongs_to :conversation
belongs_to :user
## Attributes conversation_id, user_id, seen, created_at, updated_at
end
* Message:一种跟踪内容和发件人的模型
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :sender, :class_name => "User"
## Attributes sender_id, content, conversation_id, created_at, updated_at
end
*User:具有属性 name
如何在单个查询中获取以下内容?
- limit of (5) recent messages from Message of uniq Conversation
- where
user_id
= current_user.id from ConversationParticipant- order
seen
=false
, thenupdated_at DESC
from ConversationParticipant- includes Conversation
- includes (Message sender) => User
- includes the other participant from ConversationParticipant => User
注意:includes和select很重要,因为这个问题是为了减少查询次数.
最佳答案
这里是我如何包含所有需要的模型,这个查询被翻译成 5 个 sql 查询,因为预加载没有加入(在单独的查询中运行)。
Message.joins("LEFT JOIN messages AS m ON messages.id != m.id
AND m.conversation_id = messages.conversation_id
AND messages.created_at < m.created_at")
.where('m.id IS NULL')
.joins("INNER JOIN conversation_participants AS cp
ON cp.conversation_id = messages.conversation_id
AND cp.user_id = #{user_id}")
.order("cp.seen, cp.updated_at DESC")
.limit(5)
.includes(:sender)
.includes(conversation: [{conversation_participants: :user}])
关于mysql - 来自多个模型的包含、选择、排序、限制(单个查询),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26876234/