【问题标题】:Rails: find parents with children not having an attributeRails:找到没有属性的孩子的父母
【发布时间】: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


【解决方案1】:

这个查询应该可以解决问题:

Invoice.joins(:items).where("items.status NOT IN (0, 1, 2)")

生成的 SQL 可能类似于:

SELECT "invoices".* 
FROM "invoices" 
INNER JOIN "items" 
ON "items"."invoice_id" = "invoices"."id" 
WHERE (items.status NOT IN (1, 2, 3))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多