【问题标题】:Complex Query in Rails using Model.where(...).includes(...)在 Rails 中使用 Model.where(...).includes(...) 进行复杂查询
【发布时间】:2011-09-18 07:00:16
【问题描述】:

我正在尝试通过四层(哎呀!)关联进行查询。关联如下:

(编辑:添加了关联细节,我在源代码中有它们但没有在此处包含它们)

Provider
   has_many :specialties, :through => :provider_specialties
   has_many :provider_specialties, :through => :provider_licenses
   has_many :provider_licenses

ProviderLicense
  belongs_to :provider
  has_many :specialties, :through => :provider_specialties
  has_many :provider_specialties

#linking model between ProviderLicense and Specialty
ProviderSpecialty
  belongs_to :provider_license
  belongs_to :specialty

Specialty
  has_many :provider_specialties

我的出发点是 Ryan Bates 的 RailsCast。我已经成功地搜索了一层深的关联对象,但是这一层正在杀死我。

providers = Provider.includes([:provider_languages, { :provider_licenses => :provider_specialties }]).where(conditions)

def specialties_and_conditions
  ["providers_specialties.specialty_id = ?", specialty_id] unless specialty_id.blank?
end

(编辑:下面的工作查询和连接)

Provider.joins([:specialties => { :provider_licenses => :provider_specialties }]).where(conditions)

def specialties_and_conditions
  ["specialty_id = ?", specialty_id] unless specialty_id.blank?
end

我不太明白“包含”方法的工作原理。我正在尝试使用上面的代码在 ProviderSpecialty(链接)关系中搜索 special_id,但没有成功。任何帮助将不胜感激!谢谢!

【问题讨论】:

  • 您能添加一个查询示例吗?我在关注这里的关联时遇到了麻烦。如果ProviderSpecialty 是一个连接模型,则您缺少has_many :through 关联。

标签: sql ruby-on-rails include


【解决方案1】:

您似乎将包含与连接混淆了。包含用于预加载数据以保存查询。连接的使用与 SQL 语句中的普通连接一样,可让您按关联条件进行过滤。

首先我会将它添加到您的 ProviderLicense 模型中(这让您可以更轻松地使用多对多关系):

has_many :specialties, :through => :provider_specialties

我真的不知道您要实现什么查询,但也许这会有所帮助?

Provider.joins({:provider_licenses => [:specialties]}).where('specialties.id = ?', specialty_id)

您应该查看您的开发日志中生成的 SQL 查询,然后从那里进行调整。

我还没有测试我的代码,所以它可能与语法略有不同。

【讨论】:

  • 乔尔,非常感谢!这解决了我的问题。这是一个连接问题。我还需要根据正在搜索的内容过滤正在连接的表。
猜你喜欢
  • 2011-12-31
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多