首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >活动记录使用where联接两个表

问活动记录使用where联接两个表
EN

Stack Overflow用户
提问于 2016-02-02 22:35:24
回答 1查看 112关注 0票数 1

我有一个模型

代码语言:javascript
复制
class PatientProfile < ActiveRecord::Base
  has_many :friendships

  with_options through: :friendships, source: :friend do |model|
    model.has_many :friends, -> { where(friendships: { status: 'accepted'}) }
    model.has_many :friend_requests, -> { where(friendships: { status: 'requested'}) }
    model.has_many :requested_friendships, -> { where(friendships: { status: 'requestor'}) }
  end

uids = ["123", "456"]

我想查询PatientProfile以查找uid在uids数组中的所有记录,并且这两个用户之间没有友谊的记录。

这应该可以通过join来实现,但是我在documentation中遇到了问题

编辑:

uid在PatientProfile上

在Friendships表上有两列:friend_id和patient_profile_id。我只想要PatientProfile,friend不在uids列表中,patient_profile_id也不是,比如说,1

EN

回答 1

Stack Overflow用户

发布于 2016-02-02 22:53:00

我们遗漏了一些上下文,关于你所说的没有友情记录的意思,但如果你正在寻找记录,没有与uids的友情,它将是:

代码语言:javascript
复制
PatientProfile.includes(:friendships).where(uid: [123, 456], friendships: {id: nil})

更新

或者,如果您更喜欢作用域版本:

代码语言:javascript
复制
scope :no_friendships, -> { includes(:friendships).where(friendships: {id: nil}) }

所以现在你可以这样做:

代码语言:javascript
复制
PatientProfile.no_friendships.where(uid: [123, 456])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35156244

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档