Sequel 关系和 SQL 函数

Sequel relations and SQL functions

我正在使用 Ruby Sequel,我需要查找自特定日期以来客户花费的总金额。此代码有效:

customer = Customer.where(username: params[:username]).first
unless customer
  exit
end
Purchases.where(customer: customer).and('date < ?', params[:date]).sum(:amount)

但是,我想知道是否有一种方法可以使用 Customer 和 Purchases 之间的 Model 关系而不使用 where 子句来查找 Purchases,这样代码可以看起来更清晰。

我在考虑类似 customer.Purchases.where(...).sum(...) 的方法,但它不起作用。

知道是否有办法做到这一点?

您似乎无法使用模型中声明的关联来加入 table。

Sequel documentation 仅建议以下方式生成权利 SQL:

Album.join(:artists, :id=>:artist_id)
# SELECT * FROM albums
# INNER JOIN artists ON artists.id = albums.artist_id

在你的情况下它可以是这样的:

Customer.join(:purchases, customer_id: :id).where('date < ?', params[:date]).sum(:amount)

你已经提到了

was thinking about something like customer.Purchases.where(...).sum(...) but it doesn't work.

并且在 another answer 的评论中,您提到与 customer.purchases 的关系已经存在。

那么你也应该有一个purchases_dataset-方法。它是 Sequel::SQLite::Dataset 和 returns 型号。

所以你可以试试:

customer.purchases_dataset.where('date < ?', params[:date]).sum(:amount)

(如果不行:请post你的table和模型定义来测试一下)