2014-04-19 218 views
1

User模式是這樣的:Rails的SQL查詢共同的朋友

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}" 

我有一個返回共同的朋友一軌方法,但我想要的SQL相當於:

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

回答

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} 
) 
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