我有三个表,如供应商、位置、技术和两个关联表,如供应商位置、供应商技术。
关联关系如下
供应商.rb
has_many :vendor_technologies
has_many :vendor_locations
has_many :locations, through: :vendor_locations
has_many :technologies, through: :vendor_technologies
位置.rb
has_many :vendor_locations
has_many :vendors, through: :vendor_locations
技术.rb
has_many :vendor_technologies
has_many :vendors, through: :vendor_technologies
供应商位置.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需要更多的内存(vendor表有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' }
关于mysql - 编写一个 Rails 事件记录查询来通过与两个表关联来获取所有项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28038188/