型号:
class User < ActiveRecord::Base
has_may :friends
end
class Friend < ActiveRecord::Base
belongs_to :user
end
表格
要查询:
users
两者都有:
friends.name = "Lily"
# and
friends.name = "Steven"
我想通过模型在哪里查询喜欢:
User.joins(xxx).where(xxx)
有什么办法吗?
答案 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}")
上述查询只会返回与"Lily"
和"Steven"