mysql - 编写一个 Rails 事件记录查询来通过与两个表关联来获取所有项目?

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

我有三个表,如供应商、位置、技术和两个关联表,如供应商位置、供应商技术。

关联关系如下

供应商.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/

相关文章:

php - 如何根据包含的逗号过滤从数据库中获取的值?

php - 为什么我可以使用 localhost 连接到我的托管网站数据库?

ruby-on-rails - rails 2.3.8 : Fetching objects via ActiveRecord without building all the objects

mysql - 如何使用 csv 文件更新数据库中的特定行?(rails)

ruby-on-rails - 预期响应为 < :success>, 但为 <301>

ruby-on-rails - 两个数组的交集为空

php - 在 php 中使用序列化将关联数组存储在数据库中

mysql - 一个查询中的 MAX() 和 SUM()

ruby-on-rails - 如何在 Rails 3 中使用 Cucumber/Capybara 在页面上找到图像

ruby-on-rails - 你的 Ruby 版本是 2.6.0,但是你的 Gemfile 指定了 2.5.0