如何查询选定时间段内无关联PropertyEvent的Property模型记录
问题原因
你原有代码的NOT EXISTS子查询没有和外层的Property表做关联匹配,子查询只会全局判断「是否存在任意符合时间段的PropertyEvent记录」,而非判断「当前遍历的Property是否存在符合条件的关联事件」,所以才会出现只要有任意一条匹配事件就过滤所有物业的问题。
修正方案
只需要在子查询中新增物业ID的关联条件即可,修正后的代码如下:
@properties.where('NOT EXISTS (:property_event)', property_event: PropertyEvent.where("property_events.property_id = properties.id") .where("property_events.start_date <= ?", end_date) .where("property_events.end_date >= ?", start_date) )
可选的更符合Rails风格的写法
你也可以用左连接的方式实现,可读性更高:
@properties.left_joins( "LEFT JOIN property_events ON property_events.property_id = properties.id AND property_events.start_date <= ? AND property_events.end_date >= ?", end_date, start_date ).where(property_events: { id: nil })
内容的提问来源于stack exchange,提问作者PressingOnAlways
相关产品推荐
相关产品推荐

