Select 模型基于具有特定条件的相关模型的数量
Select model based on amount of related models with certain conditions
我有一个 Post
那个 has_many :comments
。假设 Comment
具有以下字段:another_model_id
。我想要 select 个帖子,有 2 到 5 个评论 another_model_id = 10
(例如)。我尝试了几种构造但没有成功:(
我尝试过的示例:
# Invalid SQL syntax error
Post
.joins(:comments)
.select("count(comment.another_model_id = 10) as comments_count)
.where("comments_count BETWEEN 2 AND 5")
我真的不知道去哪里挖。是否可以在单个查询中实现?谢谢!
Post
.joins(:comments)
.where(comments: { another_model_id: 10 })
.group('posts.id')
.having('count(comments.id) > 2 AND count(comments.id) < 5')
使用 counter_cache
是适合您的情况的最佳做法:
在您的 Comment
模型中,您需要设置 counter_cache
:
belongs_to :post, counter_cache: true
那么你可以简单地使用这个查询:
Post.joins(:comments)
.where(comments: { another_model_id: 10 })
.where('comments_count > ? AND comments_count < ?', 2, 5)
我有一个 Post
那个 has_many :comments
。假设 Comment
具有以下字段:another_model_id
。我想要 select 个帖子,有 2 到 5 个评论 another_model_id = 10
(例如)。我尝试了几种构造但没有成功:(
我尝试过的示例:
# Invalid SQL syntax error
Post
.joins(:comments)
.select("count(comment.another_model_id = 10) as comments_count)
.where("comments_count BETWEEN 2 AND 5")
我真的不知道去哪里挖。是否可以在单个查询中实现?谢谢!
Post
.joins(:comments)
.where(comments: { another_model_id: 10 })
.group('posts.id')
.having('count(comments.id) > 2 AND count(comments.id) < 5')
使用 counter_cache
是适合您的情况的最佳做法:
在您的 Comment
模型中,您需要设置 counter_cache
:
belongs_to :post, counter_cache: true
那么你可以简单地使用这个查询:
Post.joins(:comments)
.where(comments: { another_model_id: 10 })
.where('comments_count > ? AND comments_count < ?', 2, 5)