查询在选定时间段内不存在事件的模型



考虑模型Property哪个has_many :property_events.PropertyEvent有一个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)
)

有什么想法吗?

我认为您要查找的是:

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

相关内容

最新更新