Rails一对多关联查询

时间:2016-09-14 02:46:56

标签: mysql ruby-on-rails

型号:

class User < ActiveRecord::Base
  has_may :friends
end

class Friend < ActiveRecord::Base
  belongs_to :user
end

表格

tables image

要查询:

users两者都有:

friends.name = "Lily" 
# and 
friends.name = "Steven"

我想通过模型在哪里查询喜欢:

User.joins(xxx).where(xxx)

有什么办法吗?

2 个答案:

答案 0 :(得分:0)

我认为

User.joins(:friends).where("friends.name = 'Lily' OR friends.name = 'Steven'")

会做你想要的事情

答案 1 :(得分:0)

SELECT users.id, users.name 
FROM users 
INNER JOIN friends ON users.id = friends.user_id 
WHERE friends.name IN ('Lily', 'Steven') 
GROUP BY users.id 
HAVING COUNT(*) = 2;

ActiveRecord查询

names = ['Lily', 'Steven']

User.select('users.id, users.name').joins(:friends).where(friends: { name: names }).group('users.id').having("COUNT(*) = #{names.count}")

SQLFiddle

上述查询只会返回与"Lily""Steven"

成为朋友的用户