【问题标题】:How to do OR in activerecord query with deep associations如何在具有深度关联的 activerecord 查询中执行 OR
【发布时间】:2018-04-28 16:35:10
【问题描述】:

我的位置具有关联的城市和州,其中每个城市和州都有与其关联的报告。该报告有一个属性“good_weather”。

如何查询关联城市或州具有 good_weather = true 的位置?

这是我目前所拥有的,但它不起作用:

Location.includes(city: [:report], state: [:report])
.where("cities.reports.good_weather = true OR states.reports.good_weather = true")
.references(:cities, :states, :reports)

模型如下所示:

Location has_one :city, has_one :state
City belongs_to :location, belongs_to :report
State belongs_to :location, belongs_to :report
Report has_one :city, has_one :state

PG::UndefinedTable: 错误:对表“报告”的 FROM 子句条目的引用无效 ^ 提示:表“reports”有一个条目,但不能从这部分查询中引用它。

【问题讨论】:

  • 你的模型看起来怎么样?
  • 我在帖子中添加了模型
  • 不,这不起作用 b/c 您正在跳过整个报告关联。 “列 states.good_weather 不存在”

标签: sql ruby-on-rails activerecord


【解决方案1】:

应该是这样的:

Location.joins(:city, :state)
        .joins("INNER JOIN reports 
                ON reports.good_weather = true AND 
                   (reports.id = cities.report_id OR 
                    reports.id = states.report_id)")
        .distinct

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    相关资源
    最近更新 更多