sql - Rails 包含 where 条件
问题描述
我有两个模型:
用户.rb
class User < ApplicationRecord
has_many :orders, inverse_of: :user, dependent: :restrict_with_exception
end
订单.rb
class Order < ApplicationRecord
belongs_to :user, inverse_of: :orders
end
我正在使用includes
这样的where
:
User.where(id: selected_salesmen.pluck(:id))
.includes(:orders)
.where("order.booked_at > ? AND order.booked_at < ?",
booked_at_gteq,
booked_at_lteq)
但是,它并没有给我所需users
的orders
. 任何解释为什么这不起作用?
解决方案
这可能会使方法includes
和之间有些混淆joins
,它们具有相关但非常不同的含义。
includes
将预先加载相关记录,从而防止以后多次调用数据库。它主要用于性能调整。joins
将在您的数据库查询中包含对相关表的连接,这允许您基于相关模型构建条件。
请注意,要使用连接,您需要引用表名,而不是关系名。默认情况下,ActiveRecord 将连接到一个表,该表是模型的复数名称。
因此,更改包括连接和“订单”到“订单”:
User.where(id: selected_salesmen.pluck(:id))
.joins(:orders)
.where(
"orders.booked_at > ? AND orders.booked_at < ?",
booked_at_gteq,
booked_at_lteq
)
您可能还想检查是否也selected_salesmen.pluck(:id)
返回了一些 id。
推荐阅读
- reactjs - 如何让这个 JSX 代码更通用以避免 React 中的代码重用?
- wordpress - Bootrap 4 折叠不会在 IOS Safari 上的页面滚动上折叠/消失
- database - 关于功能依赖的应用数据库问题
- html - 如何转义 HTML 元素以便输入术语在 HTML 文章中
- javascript - 为什么 Typescript 在输入 Redux-saga 调用参数时会抛出错误 - TS2339
- gradle - 在 Microsoft App-V5.1 虚拟化环境中运行 gradle 测试任务
- docker - 无法使用 java 8 安装 ElasticSearch 图像
- javascript - Chrome 扩展程序:如何获取新创建的标签 url
- ruby-on-rails - 如何限制用户删除不属于他们的帖子?
- php - 仅在 5 天内循环,而不是每小时开放的 weatherAPI