sql - ActiveRecords,我通过提供其他表的 id 过滤值
问题描述
我在弄清楚如何完成特定查询时遇到问题。
我正在尝试获取日期在其他两个日期之间的所有行(这两个日期是表中的列)。问题是这些日期都是与另一个表相关联的 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)
解决方案
You'll need to join the tables to query them:
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)
I'm curious though, what is the point of the reservation_dates
table?
推荐阅读
- python - 获取输出到 csv - python
- python-3.x - Python中的负切片步骤没有得到输出
- javascript - 在 useEffect 中使用 useState 时 Map 不是函数
- bash - Shell 脚本 - IFS 读取语法错误:意外重定向
- c - 来自 Linux 驱动程序的 32 字节 PCIe 事务
- django - 如何在 django admin 中获取自定义列的总和?
- android - 需要适用于 Unity 的 Facebook Audience Network 6.0.0 更新
- r - 在存在缺失数据的情况下,使用 pmin() 查找 r 中的最早日期
- firebase - 使用 Firebase Cloud Function 获取受 API 密钥保护的数据
- python - Sympy 用 numexpr 对 ImmutableDenseMatrix 进行lambdify