【问题标题】:Fetch clients without recent order获取没有最近订单的客户
【发布时间】:2026-01-31 01:25:01
【问题描述】:

我的应用程序中有在线订购功能,我想提取所有在上周提交订单的:clients(我有一个字段 :submitted_at 要跟踪这个)。

class Order < ApplicationRecord
    belongs_to :client
    scope :within_last_week, -> { where("submitted_at >= ?", 1.week.ago )}
end

class Client < ApplicationRecord
    has_many :orders
end

我几乎希望能够使用这个:within_last_week 范围并返回orders.within_last_week 为空的客户。

有没有办法在不遍历所有客户端的情况下做到这一点?

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    以下是解决此问题的一种方法,通过将订单和客户组合在一个关系中,同时将客户关系设置为 left_outer_joins 以获取所有客户,即使是没有订单的客户:

    Order.left_outer_joins(:client).select("clients.name, SUM(CASE WHEN submitted_at >= '12/01/2019' THEN 1 ELSE 0 END) as total_orders").having("total_orders = 0").group("clients.id")
    

    另一种方式:

    Order.left_outer_joins(:client).where("orders.submitted_at >= '12/01/2019' ").having("SUM(orders.id) = 0").group("clients.id")
    

    【讨论】:

    • 当我在控制台中尝试时,我得到一个错误:ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "?" LINE 1: ...= '12/01/2019' THEN 1 ELSE 0 END) as total_orders ? FROM "or...
    • 现在我得到错误:ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "total_orders" does not exist LINE 1: ...."deleted_at" IS NULL GROUP BY clients.id HAVING (total_orde...
    • 还是报错:ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "total_orders" does not exist LINE 1: ...."deleted_at" IS NULL GROUP BY clients.id HAVING (total_orde...
    • @JeremyThomas 我不确定为什么第一个会出现问题,我已将单引号替换为双引号。我还添加了另一种解决方法。
    • 嗯.. 他们都在控制台中仍然失败。第二个有错误:ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "orders.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "orders".* FROM "orders" LEFT OUTER JOIN "clients" O..