编写单个 rails 活动记录查询以通过关联两个表来获取所有项目?
Write a single rails active record query to get all the items by association with two tables?
我有三个 table,例如供应商、位置、技术和两个关联 table,例如 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
供应商_location.rb
belongs_to :location
belongs_to :vendor
供应商_technology.rb
belongs_to :technology
belongs_to :vendor
从上面tables,我需要,
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
对于上述需求,我需要三个不使用连接操作的单查询。因为,连接占用更多内存(供应商 table 有 12 列)
为什么要维护那么多表,我们可以这样简单:
#vendor.rb
has_many :locations
has_many :technologies
#location.rb
belongs_to :vendor
#technology.rb
belongs_to :technology
现在只加载供应商列表一次:
@vendors = Vendor.includes(:locations, :technologies)
现在,根据您的条件获取所需的数据 condition.The 这里很棒的是,根据您的条件获取数据不会触发任何额外的查询。
@vendors.first.locations.select {|x| x.place == 'India' }
@vendors.first.technologies.select {|x| x.tech_name == 'PHP' }
我有三个 table,例如供应商、位置、技术和两个关联 table,例如 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
供应商_location.rb
belongs_to :location
belongs_to :vendor
供应商_technology.rb
belongs_to :technology
belongs_to :vendor
从上面tables,我需要,
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
对于上述需求,我需要三个不使用连接操作的单查询。因为,连接占用更多内存(供应商 table 有 12 列)
为什么要维护那么多表,我们可以这样简单:
#vendor.rb
has_many :locations
has_many :technologies
#location.rb
belongs_to :vendor
#technology.rb
belongs_to :technology
现在只加载供应商列表一次:
@vendors = Vendor.includes(:locations, :technologies)
现在,根据您的条件获取所需的数据 condition.The 这里很棒的是,根据您的条件获取数据不会触发任何额外的查询。
@vendors.first.locations.select {|x| x.place == 'India' }
@vendors.first.technologies.select {|x| x.tech_name == 'PHP' }