【问题标题】:Write a single rails active record query to get all the items by association with two tables?编写单个rails活动记录查询以通过与两个表关联来获取所有项目?
【发布时间】:2015-01-20 05:12:14
【问题描述】:

我有三个表,如供应商、位置、技术和两个关联表,如 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

位置.rb

has_many :vendor_locations
has_many :vendors, through: :vendor_locations

技术.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 占用更多内存(vendor table 有 12 列)

【问题讨论】:

    标签: mysql ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    为什么你要维护这么多表,我们可以这样做:

     #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' }
    

    【讨论】:

    • 因为,'locations' 表没有 vendor_id。以及技术表也。相反,我们创建了另外两个名为 vendor_locations、vendor_technologies 的表(包含 vendor_id、location_id/technology_id)
    • 然后将这些列添加到相应的表中(技术表和位置表中的供应商 ID)。这实际上是rails的方法。仍然如果想继续您现有的设置,那么我的书面答案(使用包含方法)也将为您工作:)
    • 谢谢.. 我尝试了它对我有用的 include 方法.. :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多