Ste*_*eez -3 ruby activerecord ruby-on-rails
我想返回所有在 Rails 控制台中发表超过 1 个帖子的用户。
一个用户has_many :posts和一个帖子belongs_to :user
我已经搞乱了 where 方法,但我找不到任何东西。提前致谢!
User.joins(:posts).group('users.id').having('count(posts.id) > 1')
Run Code Online (Sandbox Code Playgroud)
该joins方法执行内部联接,从而产生与帖子有关系的所有用户,并且该group方法用于消除所有重复行。
user_id
使用ie 示例按帖子分组-
{
1 => [post_1, post_2, post_3]
2 => [post_5, post_10]
... so on
}
Run Code Online (Sandbox Code Playgroud)
then apply having(优先于where处理聚合数据)子句having("count(posts.id) > 1")
| 归档时间: |
|
| 查看次数: |
956 次 |
| 最近记录: |