2016-07-28 52 views
1

我有三個表:userslocationslocations_users,該協會如下:如何在rails中簡單地加入n對n的關聯?

user has_many locations_users 
user has_many locations :through => locations_users 

location has_many locations_users 
location has_many users :through => locations_users 

我怎麼會找到所有誰是加入了一個查詢LOCATION_ID = 5的用戶?

任何幫助,將不勝感激。

回答

1

我不知道1查詢方式,但下面的解決方案是有效的。

a = User.where("id NOT IN (?)", LocationUser.pluck("DISTINCT user_id")) 
b = LocationUser.where(location_id: 5).pluck("DISTINCT user_id") 
result = User.where(id: a+b) 
2

您可以使用LEFT OUTER JOIN。它獲取左表中的所有數據與正確的匹配數據,如果存在(如果不存在,結合縱列爲空):

User 
    .joins('LEFT OUTER JOIN locations_users ON locations_users.user_id = users.id') 
    .where('locations_users.id IS NULL OR locations_users.location_id = ?', 5) 
    .all 

Hovewer:

  • 這個查詢使用join,它的表現可以上大表差(也許兩個查詢將執行得更快 - 測試一下吧!)
  • 獲得更好的性能,確保,該指標在聯接的列
+0

你大概的意思'或'設置而不是標準中的「AND」。 –

+0

是的。糾正。 – maicher

+0

這個答案是最適合這個問題的,但左連接速度很慢 – emrahbasman