sql - 在一定条件下根据相关模型的数量选择模型
问题描述
我有Post
一个has_many :comments
。假设Comment
有以下字段:another_model_id
. 我想选择有 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')
推荐阅读
- javascript - 如何在 REACT 中保持和循环来自 Array 的 HTML 元素的样式?
- python - SDK python中Hyperledger Fabric的服务发现
- php - 如何使用 css DomPDF 从 page.html 导出 PDF
- file - 注册数据写入文件的时间
- java - 如果未选择任何选项,则以角度禁用 nb-stepper 按钮
- html - 在 Dash 中将破折号组件向右移动
- sql-server - 努力将动态 SQL 语句链接在一起而没有错误
- rust - Rust crates 的发行说明在哪里发布
- kubernetes - 终止宽限期秒未按预期工作
- elasticsearch - 将搜索短语匹配到布尔字段值