2017-02-20 42 views
2

我有關於產品的多個變種業務邏輯應用程序:發現有兩個精確的匹配記錄的許多一對多的關係

class Task < ApplicationRecord 
    belongs_to :variant 
end 

class Variant < ApplicationRecord 
    belongs_to :product 

    has_many :variant_option_values 
    has_many :option_values, through: :variant_option_values 
    has_many :prices 
end 

class Product < ApplicationRecord  
    has_many :product_option_types 
    has_many :option_types, through: :product_option_types 
    has_many :variants 
end 

class OptionValue < ApplicationRecord 
    belongs_to :option_type 
end 

class OptionType < ApplicationRecord 
    has_many :product_option_types 
    has_many :products, through: :product_option_types 
    has_many :option_values 
end 

class ProductOptionType < ApplicationRecord 
    belongs_to :product 
    belongs_to :option_type 
end 

class VariantOptionValue < ApplicationRecord 
    belongs_to :variant 
    belongs_to :option_value 
end 

的ERD看起來是這樣的: enter image description here

擁有產品product_1如何找到具有OptionValue實例option_value_1,option_value_2option_value_3的變體?請注意,該變體必須同時具有全部三個選項值,並且可以具有多於三個(但不一定)的值。

回答

1
option_values = [option_value_1, option_value_2, option_value_3] 

Variant.include(product: [option_types: :option_values]) 
    .where("option_values.id IN (?)", option_values.map(&:id)) 
    .group("products.id") 
    .having("count(*) >= ?", option_values.size) 
+0

此查詢查找具有給定選項值的產品。我想找到具有這些選項值的給定產品的變體。 – pmichna

+0

@pmichna查看更新的答案 –

+0

很好。但是,您在此假設變體只有這三個選項值。那麼,如果變體具有三個選項值,還有其他值,那麼情況如何呢? – pmichna

相關問題