【问题标题】:Querying for Model Where No Events Exist During Selected Time Period查询选定时间段内不存在事件的模型
【发布时间】:2021-11-25 10:32:26
【问题描述】:

考虑模型Property 哪个has_many :property_eventsPropertyEvent 有一个 start_date 和一个 end_date 作为日期。

我有兴趣查询空缺或在选定时间段内没有 PropertyEvent 的所有属性。

我尝试了以下方法,但该时间段内存在的第一个 PropertyEvent 会使所有属性无效,无法返回。

@properties.where('NOT EXISTS (:property_event)',
   property_event: PropertyEvent.where("property_events.start_date <= ?",end_date).
                                 where("property_events.end_date >= ?",start_date)
)

有什么想法吗?

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord


    【解决方案1】:

    我认为您正在寻找的是:

    @properties.where(
      "NOT EXISTS(
        SELECT 1 FROM property_events pe
        WHERE (pe.start_date, pe.end_date) OVERLAPS (?, ?)
      )",
      start_date,
      end_date
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 2017-02-27
      相关资源
      最近更新 更多