ActiveRecord所选查询结果的条件

时间:2018-01-09 06:09:51

标签: mysql ruby-on-rails ruby ruby-on-rails-4 activerecord

Borrower.joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id")
.where("borrowers.type='moulde_b'")
.select(" borrowers.id as id,sum(receivables.amount) as invoice_amount");

从上面的结果集中我试图在select语句之后执行 where 条件。

我正在尝试类似下面的内容,

Borrower.joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id")
    .where("borrowers.type='moulde_b'")
    .select(" borrowers.id as id,sum(receivables.amount) as invoice_amount").where("receivables.amount = 12323.23");

SUM 列上选择 条件后,确实可以这样做。

1 个答案:

答案 0 :(得分:1)

使用ActiveRecord::QueryMethods#having代替where

Borrower.
  joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id").
  where("borrowers.type = 'moulde_b'").
  select("borrowers.id as id, sum(receivables.amount) as invoice_amount").
  group("borrowers.id"). # mandatory for having
  having("invoice_amount = 12323.33")

链接这些方法的顺序并不重要,因为AR会在构建真正的SQL查询时重新排列它。