简体   繁体   English

Rails N + 1查询问题时获取与where条件关联的记录

[英]Rails N + 1 query problem when fetching associated records with where condition

I have below table structure.我有下表结构。 This is just an example这只是一个例子

UserPost => user_id, post_id, Post, Comment

So, If I try to fetch all user_posts using the below query and do where on the comments table then it fires query for the comments table因此,如果我尝试使用以下查询获取所有user_posts并在comments表上执行位置,那么它会触发对comments表的查询

user_posts = UserPost.includes(post: :comments)
user_posts.each do |up|
  post = up.post # No Query
  comments = up.comments # No query
  comments_with_condition = up.comments.where(visibility: true).order(position: :asc).first.data # Fires query for .where and .order as well.
end

So, is this the expected behavior or I am doing something wrong?那么,这是预期的行为还是我做错了什么?

How to prevent the query for each user_post如何防止对每个user_post的查询

What you can do is add another has_many to your model with a filter of what you want.您可以做的是在您的 model 中添加另一个has_many ,并使用您想要的过滤器。

# You can name this anything you want but a descriptive name helps
has_many :special_comments, -> { where(visibility: true).order(..) }, class_name: 'Comment'

...and eager load that in your query which will eager load both type of comments. ...并在您的查询中急切加载,这将急切加载两种类型的评论。 This will inevitably lead to one extra query, but it is not N+1.这不可避免地会导致一个额外的查询,但它不是N+1。

user_post = UserPost.includes(post: [:comments, :special_comments])

user_posts.each do |user_post|
  post = user_post.post
  comments = user_post.comments
  comments_with_condition = user_post.special_comments
end

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

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