我正在研究社交網絡應用程序,並試圖構建 複雜的查詢,該查詢有效地將所有用戶的朋友的登錄信息從 數據庫。基本上我需要:使用複雜的Rails 3查詢(需要:user.friends.checkins)
我重新創建(以簡化形式)下面的數據結構 參考,幷包含了多種解決方案,我發現「user.friends.checkins」,但是我覺得 喜歡我的解決方案子最佳。我希望有人能出來 一個更好的辦法......所以這裏有雲:
我想這第一次,它的工作原理,但太慢給用戶 通常每個+1000朋友:
=> Checkin.where(:user_id => self.friends)
然後我想這一點,也可以工作,是要快得多,但感覺 馬虎:
=> Checkin.joins(:user).joins('INNER JOIN "friendships" ON
"users"."id" = "friendships"."friend_id"').where(:friendships =>
{:user_id => 1})
任何幫助,您可以提供將不勝感激!感謝 提前!
===數據結構===
Users table has columns: id, name
Friendships table has columns: user_id, friend_id
Checkins table has columns: id, location, user_id
===模型===
class User
has_many :friendships
has_many :friends, :through => :friendships
has_many :checkins
end
class Friendship
belongs_to :user
belongs_to :friend, :class_name => 'User'
end
class Checkin
belongs_to :user
end
與第一解決方案的問題在於,它需要3秒鐘的加載由「self.friends」返回500-1000 ActiveRecord對象。它不是SQL很慢(SQL只需要2-3ms),它是ActiveRecord。我剛剛發佈了另一個解決方案,我發現這似乎是一種改進。 – 2010-10-15 07:24:48