2016-07-26 52 views
0

我正在使用Sequel ORM。我有三个表格,'类别','商人','产品'。如何在Sequel ORM for Ruby中执行多个连接

下面是型号:

class Product < Sequel::Model 
    many_to_one :merchants 
end 

class Merchant < Sequel::Model 
    many_to_one :category 
end 

我需要获取那些特定类别的产品。我该如何做一个JOIN?

如果我需要的产品为特定的商户,我可以很容易做到:

@merchant = Merchant.first(:id=>1) 
@merchant.products.each do |s| 
... 
end 

但我怎样才能在一个类别的产品时,类别涉及到商家和商家的相关产品表?

回答

0

获取一个类别,迭代属于该类别的商户,并推/该商家的产品追加到一个数组:

products = [] 
category = Category.find(:id=>1) 
category.merchants.each do |m| 
    p<<m.products 
end 
+0

我认为这将需要重复m.products再次,例如,'m.pr oducts.each do | m | ... end'。有没有办法做一个JOIN获得类似的结果? –

3

这里有一种方法:

Product. 
    select_all(:products). 
    association_join(:merchant). 
    where(:category_id=>category.id) 

但它可能是最容易的只是添加一个关联:

Category.many_to_many :products, 
    :join_table=>:merchants, 
    :right_key=>:id, 
    :right_primary_key=>:merchant_id 

category.products 
相关问题