Rails SQL查询共同的朋友

时间:2014-04-19 21:43:19

标签: sql ruby-on-rails

我的User模型如下所示:

has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed

has_many :reverse_relationships, foreign_key: "followed_id",
                                 class_name:  "Relationship",
                                 dependent:   :destroy
has_many :followers, through: :reverse_relationships, source: :follower

我想要的是原始SQL查询,以获取给定用户跟随并被跟踪的用户。

目前我只是获得了我正在关注的用户ID:

followed_user_ids = "SELECT followed_id FROM relationships
                             WHERE follower_id = #{user.id}"

我有一个rails方法可以返回共同的朋友,但我想要SQL等价物:

def mutual_friends
    # interesect both arrays to find similar elements
  self.followed_users & self.followers
end

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效

SELECT followed_id
FROM relationships
WHERE follower_id = #{user.id} AND followed_id IN (
    SELECT follower_id FROM relationships WHERE followed_id = #{user.id} 
)

答案 1 :(得分:0)

请像这样使用它,让我知道它是否适合你。

has_many :company_friendships, autosave: true
has_many :company_friends, through: :company_friendships, autosave: true
has_many :inverse_company_friendships, class_name: "CompanyFriendship", foreign_key: "company_friend_id", autosave: true
has_many :inverse_company_friends, through: :inverse_company_friendships, source: :company, autosave: true  

def mutual_company_friends
  Company.where(id: (company_friends | inverse_company_friends).map(&:id))
end