带有嵌套模型和派生列值的ActiveRecord查询? [英] ActiveRecord query with nested models and derived column values?
本文介绍了带有嵌套模型和派生列值的ActiveRecord查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下关系:
class Order < ActiveRecord::Base
has_many :item_selections, :dependent => :destroy
has_many :inventory_items, :through => :item_selections
end
class InventoryItem < ActiveRecord::Base
has_many :item_selections, :dependent => :destroy
has_many :orders, :through => :item_selections
end
class ItemSelection < ActiveRecord::Base
belongs_to :order
belongs_to :inventory_item
end
<我试图在下面创建与此SQL查询等效的ActiveRecord,然后加载* total_weight *& * total_volume *列到实例变量中:
I am trying to create the ActiveRecord equivalent of this SQL query below and then load the sum of the *total_weight* & *total_volume* columns into an instance variable:
select t1.quantity, t2.volume, t2.weight,
t2.volume * t1.quantity as total_volume,
t1.quantity * t2.weight as total_weight
from orders t0
inner join item_selections t1 on t0.id = t1.order_id
inner join inventory_items t2 on t1.inventory_item_id = t2.id
where t0.id = <id_val>
是否有使用ActiveRecord获取这些值的正确方法?
Any idea on the right way to get these values using ActiveRecord?
推荐答案
这应该起作用:
orders = Order.select('orders.*, t1.quantity, t2.volume, t2.weight, t2.volume * t1.quantity as total_volume, t1.quantity * t2.weight as total_weight').joins('inner join item_selections t1 on orders.id = t1.order_id, inner join inventory_items t2 on t1.inventory_item_id = t2.id').where(:id => id_val)
使用像这样的自定义选择将其他选择的东西添加为返回对象的属性,因此您可以像引用它们一样是订单对象的字段来引用它们:
Using a custom select like this adds the other things selected as attributes of the returned objects, so you can reference them as though they were fields of the order object:
@total_volume_sum = orders.sum(:total_volume)
@total_weight_sum = orders.sum(:total_weight)
这篇关于带有嵌套模型和派生列值的ActiveRecord查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文