我有一个包含用户、关系、帖子和喜欢的应用程序。
我的模型是:
class User
has_many :posts
has_many :likes
has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy
end
class Post
belongs_to :user
has_many :likes
end
class Like
belongs_to :user
belongs_to :post
end
class Relationship
belongs_to :follower, :class_name => "User"
belongs_to :followed, :class_name => "User"
end
所以我想找到至少 100 个喜欢我当前帖子的用户:
friends = User.find(user.followers).likes.where(:post => @post, :limit => 100)
It's a simple but not optimized query if there are a lot of users, posts, likes, etc. in DB.
How can I optimize the query (or models) to increase speed and to decrease query's time execution?