[英]Rails One-to-many association Query
Models: 楷模:
class User < ActiveRecord::Base
has_may :friends
end
class Friend < ActiveRecord::Base
belongs_to :user
end
Tables: 表格:
To Query: 要查询:
users
which both has: 都具有的
users
:
friends.name = "Lily"
# and
friends.name = "Steven"
I want by Model Where Query like: 我想要按Model Where Query这样:
User.joins(xxx).where(xxx)
Is there any way to do? 有什么办法吗?
I think 我认为
User.joins(:friends).where("friends.name = 'Lily' OR friends.name = 'Steven'")
will do what you are looking for 会做你想要的
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 Query ActiveRecord查询
names = ['Lily', 'Steven']
User.select('users.id, users.name').joins(:friends).where(friends: { name: names }).group('users.id').having("COUNT(*) = #{names.count}")
The query above will return you only the users who are friends with "Lily"
and "Steven"
上面的查询将仅向您返回与
"Lily"
和"Steven"
成为好友的用户
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.