Rails:找到少于X关联的模型,也包括没有任何关联的模型(Rails: Find model with less than X associations, also including the on

编程入门 行业动态 更新时间:2024-10-23 12:38:52
Rails:找到少于X关联的模型,也包括没有任何关联的模型(Rails: Find model with less than X associations, also including the ones without any)

我正试图让我们的用户分组。

用户型号:

Class User has_many :orders

订购型号:

Class Order has_many :orders

现在让我们说,我想让一小部分用户的订单少于5个。

User .joins('left outer join orders on users.id = orders.user_id') .group(:user_id) .having('count(user_id) <= ?' 5)

但是,这只会吸引至少有一个订单的用户。 我还需要做些什么来包括没有任何订单的用户?

I'm trying to make a way to group our users into segments.

User model:

Class User has_many :orders

Order model:

Class Order has_many :orders

Now let's say that I want to make a segment of users who have made less than 5 orders.

User .joins('left outer join orders on users.id = orders.user_id') .group(:user_id) .having('count(user_id) <= ?' 5)

However this just grabs the users that have at least 1 order. What do I need to do to also include users who don't have any orders?

最满意答案

我没有测试过,所以试试这个,让我知道。

User.joins( :orders ).group( 'users.id' ).having( 'count( order_id ) < 5' )

我相信你正在计算错误的列。 你应该计数order_id 。 随意评论,如果我错了,或者如果这引发任何错误。

Figured it out myself. "eager_load" includes everything.

User.eager_load(:orders).group("users.id").having("count(orders.id) >= ?", 5)

更多推荐

本文发布于:2023-08-07 18:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465100.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   没有任何   Rails   Find   including

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!