【问题标题】:ActiveRecords where I filter the the value of by giving ids of other tableActiveRecord,我通过提供其他表的 id 过滤值
【发布时间】:2021-02-20 22:19:58
【问题描述】:

我在弄清楚如何完成特定查询时遇到了问题。

我正在尝试获取日期在其他两个日期之间的所有行(这两个日期是表中的列)。问题是这些日期都是与另一个表相关联的 ID(外键)。

这两个表的结构是:

**ReservationDate**

 - id
 - date (which is the date)

**Reservation**

 - id
 - from_date_id
 - to_date_id

如果他们不是日期表的 id,我会简单地完成

Reservation.where("(?) BETWEEN from_date AND to_date",date)

但是,它们是 ReservationDate 表的 id,我想不出办法。

理想情况下,类似的东西会起作用。但事实并非如此。

Reservation.where("(?) BETWEEN from_date_id.date AND to_date_id.date",date)

【问题讨论】:

    标签: sql ruby-on-rails ruby sqlite activerecord


    【解决方案1】:

    您需要连接这些表来查询它们:

    Reservation.
      joins(
        'reservation_dates AS from_dates ON reservations.from_date_id = from_dates.id').
      joins(
        'reservation_dates AS to_dates ON reservations.to_date_id = to_dates.id').
      where('(?) BETWEEN from_dates.date AND to_dates.date', date)
    

    不过我很好奇,reservation_dates 表的意义何在?

    【讨论】:

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