【问题标题】:How do I find the user that has both fleas and ticks :through pets?如何找到既有跳蚤又有蜱虫的用户:通过宠物?
【发布时间】:2011-07-15 01:26:41
【问题描述】:

好的,我最近有great answers to a question about how to do some sub-selects in an activerecord query。我现在有一个更复杂的情况,我无法弄清楚。

我想在 3 个与 :through 具有多对一关系的表中进行搜索,例如

class User << ActiveRecord::Base
  has_many :pets
  has_many :parasites, :through => :pets
end

class Pet << ActiveRecord::Base
  has_many :parasites
  belongs_to :users
end

class Parasite << ActiveRecord::Base
  belongs_to :pets
end

现在假设我有一些这样的数据

users

id        name
1         Bob
2         Joe
3         Brian

pets

id        user_id  animal
1         1        cat
2         1        dog
3         2        cat
4         3        dog

parasites

id        pet_id    bug
1         1         tick
2         2         flea
3         3         tick
4         3         flea
5         4         tick

我想做的是创建一个活动记录查询,该查询将返回一个用户,该用户的宠物既有蜱又有跳蚤(即用户 2 - Joe)

这远远超出了我的 activerecord 和 sql 技能,我什至不会费心向你展示我迄今为止的拙劣尝试。

【问题讨论】:

  • “同时有跳蚤和蜱虫的用户” - 必须是最好的 SO 头衔之一!

标签: sql ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:

这和上一个问题差不多,你只需要在子选择上再深一层:

User.where('id IN (SELECT user_id FROM pets WHERE
  id IN (SELECT pet_id FROM parasites WHERE bug = ?) AND
  id IN (SELECT pet_id FROM parasites WHERE bug = ?))', 'flea', 'tick')

【讨论】:

  • 哦,太好了,谢谢!我开始弄清楚这一点。我注意到这次加入消失了。回到上一个问题,你的答案实际上在没有加入的情况下效果更好(重复消失,我想我理解)。
  • 或在 Squeel 中。 User.where{id.in(Pet.where{id.in(Parasite.where{bug == 'flea'}.select{pet_id} & Pet.where{id.in(Parasite.where{bug == 'tick '}.select{pet_id})}.select{user_id})}。Squeel 看起来绝对棒极了!
猜你喜欢
  • 2021-05-29
  • 2016-11-15
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多