鉴于以下模型,使用rails 2.1:
class Product < ActiveRecord::Base
has_many :from_sources, :class_name => 'ProductSource', :foreign_key => 'to_product_id'
has_many :to_sources, :class_name => 'ProductSource', :foreign_key => 'from_product_id'
has_many :from_products, :through => :from_sources
has_many :to_products, :through => :to_sources
end
class ProductSource < ActiveRecord::Base
belongs_to :from_product
belongs_to :to_product
end
class Supplier < ActiveRecord::Base
has_many :products
end
我真的找不到过滤来自其他供应商的供应商产品的方法。
让我举几个数据的例子
我想过滤:来自供应商SC的产品,只有来自SB的产品。
谢谢!
答案 0 :(得分:0)
不确定我是否理解您的架构,但我认为您至少需要将您的产品归属于供应商,因此您可以根据供应商提供的产品表进行过滤:
Product.find(:conditions => {:supplier_id => @sb.id})
你现在可以:
所以实际的SQL查询应如下所示:
SELECT DISTINCT products.id, (etc...)
FROM products, product_sources
INNER JOIN product_sources
ON products.from_sources = product_sources.id
LEFT JOIN products AS source
ON product_sources.id = source.id
WHERE products.supplier_id = (SC's id) AND source.supplier_id = (SB's id)
很抱歉,但我对rails 2查询界面并不是很熟悉(rails 3太棒了),所以我说不出更多,但我认为这是正确的逻辑。