繁体   English   中英

Rails 在 jsonb 多个 where 条件中查找子字符串

[英]Rails find substring in jsonb multiple where conditions

假设我有包含列ingredients jsonb列类型的表recipes 示例记录:

{
  id: 1,
  ingredients: [
    'eggs',
    'fragrant bread',
    'fresh tomatoes'
  ]
}

如何在where条件下检索带有子字符串的记录? 例如:

ingredients = ['egg', 'tomato']
Recipe.where('ingredients ?& array[:keys]', keys: ingredients)

我在尝试:

ingredients = ['egg', 'tomato']
Recipe.where("ingredients @> ARRAY[?]::varchar[]", ingredients).count

但我收到此错误:

ERROR:  operator does not exist: jsonb @> character varying[] (PG::UndefinedFunction)

我真的会考虑只使用两个表,因为这令人讨厌的 JSON 反模式。

class Recipe
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients

  def self.with_ingredients(*ingredients)
    binds = Array.new(ingredients.length, '?')
    sql = "ingredients.name ILIKE ANY(ARRAY[#{binds.join(,)}])"
    joins(:ingredients)
      .where(
        sql,
        *ingredients.map { |i| "%#{i}%" }
      )
  end
end
class RecipeIngredient
  belongs_to :ingredient
  belongs_to :recipe
end
class Ingredient
  has_many :recipe_ingredients
  has_many :recipes: through: :recipe_ingredients
end

这使您可以在recipies.name上使用有效的索引、合理的查询并避免非规范化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM