简体   繁体   English

检索模型中的记录时如何减少相同查询的数量

[英]How to reduce number of identical queries when retrieving records in model

I have started using query-analyzer and it's warning me about identical queries. 我已经开始使用查询分析器 ,它警告我有关相同的查询。

For context, I am loading 25 "posts" on the page, and the current user can "star" a post: 对于上下文,我在页面上加载了25个“帖子”,当前用户可以“加注星标”一个帖子:

0.018s 25 identical queries SELECT SQL_NO_CACHE N AS one FROM 'stars' WHERE 'stars'.'post_id' = N AND 'stars'.'user_id' = N LIMIT N 0.018s 25个相同的查询在 SELECT SQL_NO_CACHE N AS one FROM 'stars' WHERE 'stars'.'post_id' = N AND 'stars'.'user_id' = N LIMIT N

This is the method in the User model: 这是用户模型中的方法:

def has_starred_post?(post)
  return false if post.nil?

  Star.where(post_id: post.id, user_id: self.id).exists?
end

How can I satisfy this warning by reducing the number of queries? 如何通过减少查询数量来满足此警告?


Update: 更新:

Per Taryn East's tip, I updated the User model method to: 根据Taryn East的技巧,我将User模型方法更新为:

def has_starred_post?(post)
  return false if post.nil?

  self.stars.where(post_id: post.id).exists?
  # OR post.stars.where(:user_id => self.id).exists?
end

Although this allows me to associate/cache the stars belonging to the User, I still have to use where to check if any of those stars belong to the post. 尽管这使我可以关联/缓存属于该用户的星标,但是我仍然必须使用where来检查where任何星标是否属于该帖子。 Right? 对?

You can reduce this kind of duplicate query by using associations - which are automatically cached by Rails. 您可以通过使用关联来减少这种重复查询-关联会由Rails自动缓存。

class Post
   has_many :stars


class User
   def has_starred_post?(post)
     return false if post.nil?

     post.stars.exists?
   end

Or re-organise so it makes sense to your actual object model... 或重新组织,以使其对您的实际对象模型有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM