我有三个表,如供应商,位置,技术和两个关联表,如vendor_location,vendor_technology。
协会如下
vendor.rb
has_many :vendor_technologies
has_many :vendor_locations
has_many :locations, through: :vendor_locations
has_many :technologies, through: :vendor_technologies
location.rb
has_many :vendor_locations
has_many :vendors, through: :vendor_locations
technology.rb
has_many :vendor_technologies
has_many :vendors, through: :vendor_technologies
vendor_location.rb
belongs_to :location
belongs_to :vendor
vendor_technology.rb
belongs_to :technology
belongs_to :vendor
从上表中,我需要,
1) vendors in locations (india)
need: list of vendors
2) vendors in technology (php)
need: list of vendors
3) vendors in technology and location (php and india)
need: list of vendors
对于上述要求,我需要三个单独的查询而不使用连接操作。因为,join需要更多内存(供应商表有12列)
答案 0 :(得分:2)
为什么要维护这么多表,我们可以这样做:
#vendor.rb
has_many :locations
has_many :technologies
#location.rb
belongs_to :vendor
#technology.rb
belongs_to :technology
现在只加载供应商列表一次:
@vendors = Vendor.includes(:locations, :technologies)
现在,根据您的情况获取所需的数据。这里的好处是根据您的条件获取数据不会触发任何额外的查询。
@vendors.first.locations.select {|x| x.place == 'India' }
@vendors.first.technologies.select {|x| x.tech_name == 'PHP' }