首页 > 解决方案 > rails 内的嵌套值查询 where

问题描述

查询 @products = @products.offset(offset).limit(@limit).where(status: "visible").where.not(inventory: [nil, {}])

我该如何添加 where.not((product.inventory.length == 1 and product.inventory.first[1]["quantity"].to_i == 0)))))

即如何检查财产的长度,inventory如果1检查第一个条目的数量,并满足上述条件?

标签: ruby-on-railsruby-on-rails-4ruby-on-rails-5

解决方案


使用 jsonb 运算符

@products = 
  @products
    .offset(offset)
    .limit(@limit)
    .where(status: "visible")
    .where.not(inventory: [nil, {}])
    .where.not("ARRAY(select (jsonb_each(inventory)).value->>'quantity' as integer)='{0}'")

推荐阅读