簡體   English   中英

通過關聯找到記錄

[英]found record through association

我有這樣的造型

class Room
  include Mongoid::Document
  field :name, type: String
  has_many :messages
end

class Message
  include Mongoid::Document
  field :content, type: String
  belongs_to :room
end

我需要找到在過去24小時內發送最多消息的前3個會議室,但我不知道從哪里開始。
也許有地圖/減少?

使用Mongoid聚合嘗試此操作

Room.collection.aggregate(
  {
    "$match" => {"$messages.created_at" => {"$gte" => 1.day.ago}},
    "$group" => { 
      _id: '$messages', count: {"$sum" => 1}
    },
    { "$sort" => { count: -1 } }
  }
)

我解決了這個

match = { "$match" => { "created_at" => { "$gte" => 1.day.ago } } }
group = { "$group" => { _id: '$room_id', count: {"$sum" => 1 } } }
sort = { "$sort" => { count: -1 } }
limit = { "$limit" => 3 }

Message.collection.aggregate([match, group, sort, limit])

絕對有更好的方法可以做到這一點,但是我認為這段代碼應該可以工作:

Room.select("rooms.*, count(messages) as count").joins(:messages).where("messages.created_at < ?", 1.day.ago).group("rooms.id").order("count DESC").limit(3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM