如何基于许多一对多的关系,选择用户子集? [英] How to select subset of users based on many-to-many relationship?

查看:128
本文介绍了如何基于许多一对多的关系,选择用户子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户组织有很多-to-many关联到关系

一位在相关模型中的变量是一个叫布尔成员。结果
A 用户可以在相关模型多次为用户发生可与多个组织

我怎样才能从所有的用户选择一个随机的实例:1)没有与任何组织的关系(所以不要在相关模式发生),加上二)用户这确实有关系一个组织,但对他们来说,成员= FALSE 所有的他们与组织的关系?

我在想是这样的:

 用户= User.where(relationship_id =零|| ???).offset(兰特(0..100))。第一


解决方案

我将做到这一点。


  1. User.joins(LEFT JOIN ON relationships.user_id = users.id关系)。在这里('relationships.user_id IS NULL')。偏移(兰特(0..100 ))。第一个


  2. 是这样的:

      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

  1. User.joins("LEFT JOIN relationships ON relationships.user_id = users.id").where('relationships.user_id IS NULL').offset(rand(0..100)).first

  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆