从关联表中查询属性,使用DataMapper计算值

时间:2012-11-21 10:37:22

标签: ruby datamapper ruby-datamapper

人员表

------------------------------------------------------------
id  |  name  |  cost_price  |  sell_price  |  product_id  |
------------------------------------------------------------
 1    person1    10000         20000            1
 2    person2    20000         30000            2
 3    person3    30000         40000            3

产品表

--------------
id  |  name  | 
--------------
 1   product1 
 2   product2 
 3   product3 
我的SQL查询
select name, (cost_price - selling_price) as profit, products.name
from persons
inner join products on persons.product_id = products.id 
where product.id = 1
order by product.name asc

我无法在Data Mapper中复制这个,这是我尝试过的(我已经正确定义了模型及其关联)

Person.all( 

# SQL Join equivalent
  Person.product.id => 1,  

# products.name how to define that ?
# Also can we directly take cost_price-selling_price as profit or 
# we need to model the resultset ?
  :fields => ['id', 'name', 'cost_price', 'selling_price']

# How do I order by product.name ?
  :order => []
)

1 个答案:

答案 0 :(得分:1)

获取人:

person = Person.first id: 1
# or
person = Person[1]

person现在包含所有相关产品(DataMapper为您做所有联接工作),
你只需要获取/列出它们:

products = person.products order: :name.asc

关注(cost_price - selling_price) as profit
您可以在Person模型中添加方法,如下所示:

class Person
  # ...

  def profit
    cost_price - selling_price
  end
end

迭代人员/产品:

Person.each do |person|
  puts person.name
  puts " Profit: #{person.profit}"
  puts " Products:"
  person.products.all(order: :name).each do |product|
    puts "  #{product.name}"
  end
end