gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:25:28 25 4
gpt4 key购买 nike

我已经开始使用 query-analyzer它警告我有关相同的查询。

就上下文而言,我正在页面上加载 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

这是用户模型中的方法:

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

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

如何通过减少查询数量来满足此警告?

<小时/>

更新:

根据 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

虽然这允许我关联/缓存属于用户的星星,但我仍然必须使用 where 来检查这些星星是否属于该帖子。对吗?

最佳答案

您可以通过使用关联来减少这种重复查询 - Rails 自动缓存关联。

class Post
has_many :stars


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

post.stars.exists?
end

或者重新组织,使其对您的实际对象模型有意义......

关于mysql - 在模型中检索记录时如何减少相同查询的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38297694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com