Rails 3 query on condition of an association's count

后端 未结 3 2047
清歌不尽
清歌不尽 2020-12-02 15:42

In Rails 3 with mysql, suppose I have two models, Customers and Purchases, obviously purchase belongs_to customer. I want to find all the customers with 2 orders or more. I

3条回答
  •  离开以前
    2020-12-02 16:33

    This is a bit more verbose, but if you want Customers where count = 0 or a more flexible sql, you would do a LEFT JOIN

    Customer.joins('LEFT JOIN purchases on purchases.customer_id = customers.id').group('customers.id').having('count(purchases.id) = 0').length
    

提交回复
热议问题