我使用的是续集ORM。我有三个表,‘类别’,‘商家’,‘产品’。
以下是模型:
class Product < Sequel::Model
many_to_one :merchants
end
class Merchant < Sequel::Model
many_to_one :category
end我需要获取特定类别的产品。我如何为它做一个连接呢?
如果我需要特定商家的产品,我可以很容易地做到:
@merchant = Merchant.first(:id=>1)
@merchant.products.each do |s|
...
end但是,当类别与商家相关,商家与products表相关时,如何获取类别中的产品?
发布于 2016-07-27 00:20:01
这里有一种方法:
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发布于 2016-07-26 15:01:20
获取一个类别,遍历属于该类别的商家,并将该商家的产品推入/附加到一个数组中:
products = []
category = Category.find(:id=>1)
category.merchants.each do |m|
p<<m.products
endhttps://stackoverflow.com/questions/38579902
复制相似问题