ActiveRecord的查询:订单,款额上包含的模型 [英] ActiveRecord query: order by a sum on an included model
本文介绍了ActiveRecord的查询:订单,款额上包含的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 在项目的has_many:项目
- 项目belongs_to的:项目
我试图让该项目依各自项目的总价。是这样的:
Project.includes(:项目).order('SUM(items.price))
通过这个code,ActiveRecord的只返回的第一个项目。我在想什么?
解决方案
Project.find_by_sql
选择的项目。*
从项目
左连接(
选择PROJECT_ID,总和(价格)为items_sum
从项目
通过PROJECT_ID组)的款项上
project.id = sums.project_id
为了通过sums.items_sum
上面的SQL应该很好地工作在大多数数据库系统(MySQL和PostgreSQL,...)。
AR记录包括
主要是用作立即加载解决方案。而且我不知道你是否可以用这种方式 - 订购父表中的记录
- Project has_many :items
- Item belongs_to :project
I'm trying to get the projects sorted by the total price of their respective items. Something like:
Project.includes(:items).order('SUM(items.price)')
With this code, ActiveRecord returns only the first project. What am I missing?
解决方案
Project.find_by_sql "
select projects.*
from projects
left join (
select project_id, sum(price) as items_sum
from items
group by project_id) as sums on
project.id = sums.project_id
order by sums.items_sum
Above SQL should work well on most DB systems (MySQL, PostgreSQL, ...).
AR record includes
is mostly used as eager loading solution. And I am not sure if you can use it that way - to order records of parent table.
这篇关于ActiveRecord的查询:订单,款额上包含的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文