2012-11-21 1 views
0

사람 표쿼리, 계산 된 값은 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 

데이터 매퍼, 이것은 내가 시도한 것입니다 (모델을 &에 올바르게 정의했습니다).
그냥 가져 오기 위해 필요 가 /을 나열 (DataMapper 모두가 당신을 위해 물건을 가입하고)

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

person 이제 모든 관련 제품이 포함되어 있습니다 :

 
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

사람이 가져

products = person.products order: :name.asc 

관련하여 (cost_price - selling_price) as profit
안에 메소드를 추가 할 수 있습니다. 이런모델 :

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 
+0

우리가 단일 쿼리에서 그것을 할 수 없어 보인다. 아이디어를 가져 주셔서 고마워요.이게 도움이됩니다. –

+0

죄송합니다. 실수로 person.id 대신 SQL 쿼리에서 product.id가 어디에 있는지 질문을 수정했습니다. 따라서 조인 당 레코드를 찾아야 만합니다. 제품 이름 가져 오기? –

+0

죄송합니다. 'Person :: all (...) .each do | person |','...'는 필터,'id : 1','name :/Bob /'또는': profit.gt N' 등 –