簡體   English   中英

如何獲得在Rails / MongoId中的數組中指定了所有用戶的所有組?

[英]How do I get all the groups that have all the users I specified in an array in Rails/MongoId?

我有一個Groups的集合,一個Users的集合和一個GroupUsers的集合,其中包含2個字段: group_iduser_id 我想找到具有我在數組中指定的所有用戶的所有組。

例。 如果我做:

group1 << user1
group1 << user2

當我嘗試找到包含user1user2user3 ,我應該沒有任何結果。 但是如果要包含user1user2的組,我應該得到group1

我試過了:

GroupUser.where(:user.in => [user1, user3]).group_by(&:group)

但這將返回group1因為user1是該組的成員。

謝謝您的幫助。

我們終於找到了解決方案:

class Group
  embeds_many :users, class_name: "GroupUser"
  scope :with_status, -> (status) do
    where(:"users.status" => status )
  end
end

class User
end

class GroupUser
  embedded_in :group
  belongs_to :user
end

然后是Group.where(:"users.user_id".all => [user1.id, user2.id])

非常感謝您的幫助。

(僅適用於ActiveRecord):您可以在Group類中同時使用havinggroup語句來定義此范圍:

class Group < ActiveRecord::Base
  scope :with_all_users, ->(users) do
    joins(:users)
    .where(users: {id: users.map(&:id)})
    .group('groups.id')
    .having('count(users.id) = ?', users.size)
  end
end

然后,您可以像這樣使用它來獲取具有您作為數組或集合提供的所有用戶的所有組:

Group.with_all_users([user1, user2, user3])

看起來您只需要使用all而不是in 請參閱選擇文檔中的第一個條目。

可查詢#全部

添加$ all選擇。 文檔必須匹配數組中提供的所有值

queryable.all(field: [ 1, 2, 3 ])

暫無
暫無

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

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