我会很简短,直截了当。我正在尝试将三个表连接在一起,以获得所有未归档客户的总开票时间乘以开票费率。这是我目前在我的控制器中拥有的:
@total_due = Client.find(:all, :joins => [:invoices, :invoice_line_items], :select => "SUM(invoice_line_items.hours * invoice_line_items.rate) as total", :group => "clients.archive, invoices.paid_status HAVING clients.archive = false AND invoices.paid_status = false")
我的模型如下所示:
# /models/clients.rb
class Client < ActiveRecord::Base
has_many :invoices
has_many :invoice_line_items, :through => :invoices
end
# /models/invoices.rb
class Client < ActiveRecord::Base
belongs_to :client
has_many :invoice_line_items
end
# /models/invoice_line_items.rb
class Client < ActiveRecord::Base
belongs_to :invoice
end
因此,正如您从我的控制器中的代码中看到的那样,我正在尝试获取与未归档客户相关的所有发票的总工时费率,但他们尚未付款。我的控制器中的上述代码在某处复制数据,因为我的数字比它应该的高很多。
我正在尝试构建的查询是这样的:
SELECT SUM(invoice_line_items.hours * invoice_line_items.rate) AS total FROM clients INNER JOIN invoices ON clients.id = invoices.client_id INNER JOIN invoice_line_items ON invoices.id = invoice_line_items.invoice_id GROUP BY clients.archive, invoices.paid_status HAVING clients.archive = false AND invoices.paid_status = false
有人可以解释或弄清楚为什么我在我的 rails 查询中得到重复的数据吗?我有一种感觉,它只是加入表格的方式与我预期的不同。我对 Rails 也还是很陌生。谢谢!
更新:这是 rails 正在生成的查询:
select sum(invoice_line_items.hours * invoice_line_items.rate) as total
from clients
inner join invoices on invoices.client_id = clients.id
inner join invoices invoices_clients_join on invoices_clients_join.client_id = clients.id
inner join invoice_line_items on invoice_line_items.invoice_id = invoices_clients_join.id
group by clients.archive, invoices.paid_status
having clients.archive = false and invoices.paid_status = false