如何基于许多一对多的关系,选择用户子集? [英] How to select subset of users based on many-to-many relationship?
问题描述
用户
和组织
有很多-to-many关联到关系
。
一位在相关
模型中的变量是一个叫布尔成员
。结果
A 用户
可以在相关
模型多次为用户发生
可与多个组织
。
我怎样才能从所有的用户选择一个随机的实例
:1)没有与任何组织的关系
(所以不要在相关
模式发生),加上二)用户
这确实有关系一个组织,但对他们来说,成员= FALSE
为所有的他们与组织的关系?
我在想是这样的:
用户= User.where(relationship_id =零|| ???).offset(兰特(0..100))。第一
我将做到这一点。
-
User.joins(LEFT JOIN ON relationships.user_id = users.id关系)。在这里('relationships.user_id IS NULL')。偏移(兰特(0..100 ))。第一个
-
是这样的:
member_ids = Relationship.where(成员:真).pluck(:USER_ID).uniq
用户= User.where.not(ID:member_ids)#或on Rails的&LT User.where('?ID未在()',member_ids); 4
User
and Organization
have a many-to-many association through Relationship
.
One of the variables in the Relationship
model is a boolean called member
.
A user
can occur in the Relationship
model multiple times as a user
can be related to multiple organizations
.
How can I select a random instance from all the users
that 1) don't have a relationship with any organization
(so don't occur in the Relationship
model) plus 2) those users
that do have a relationship with an organization but for whom member = false
for all their relationships with organizations?
I was thinking of something like:
user = User.where( relationship_id = nil || ??? ).offset(rand(0..100)).first
I will do this
User.joins("LEFT JOIN relationships ON relationships.user_id = users.id").where('relationships.user_id IS NULL').offset(rand(0..100)).first
Something like:
member_ids = Relationship.where(member: true).pluck(:user_id).uniq users = User.where.not(id: member_ids) # or User.where('id NOT in (?)', member_ids) on Rails < 4
这篇关于如何基于许多一对多的关系,选择用户子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!