我有三个表,例如vendor,location,technology和两个关联表,例如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列)
为什么您要维护这么多表,我们可以像这样简单地做:
#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' }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句