【发布时间】:2020-05-20 09:19:55
【问题描述】:
- Invoice has_many Item
- Item belongs_to Invoice
我正在尝试查找所有不包含状态为 0、1 或 2 的项目的发票。
例子:
Invoice 1
Items:
Item 1 - status 0
Item 2 - status 8
Invoice 2
Items:
Item 1 - status 6
Item 2 - status 8
查询应返回 Invoice 2,因为其中没有任何一项具有 [0, 1, 2] 中的状态。
我试过了,但它不起作用:
Invoice.includes(:items).where.not(items: { status: [0, 1, 2] })
但它不起作用。它不断返回包含处于禁止状态的项目的发票。
【问题讨论】:
-
Invoice.where(id: Item.where.not(status: [0,1,2]).pluck('invoice_id'))
-
是否可以有 1 个 SQL 查询而不是两个?
-
事实上数据库很大,采摘需要很多时间。
-
@Yassine 应该是
select('invoice_id')而不是pluck,我的错 -
正在生成的
Invoice.includes(:items).where.not(items: { status: [0, 1, 2] })的 SQL 查询是什么?
标签: sql ruby-on-rails ruby activerecord psql