查询hstore字段,其中值存在并等于x



我有一个Widgets模型,该模型具有大约3个核心活动记录。一列名为" form_values",其格式:

"{"a":1,"b":2}"
{"a" => "1", "b" => "2", "product_type" => "1"}.to_json

我需要查询所有form_values包含键a的活动记录,其值为1。

我写了一些不起作用的东西:

required_widgets = Widget.find_by_sql("select id from  (select id, form_values from widgets where form_values!= '' and form_values::jsonb?'' and form_values::json->>'product_type' = '1') as required_widgets where (form_values::json->'a')::jsonb?'1' ")

如果您使用的是PostgreSQL支持的hstore数据类型,则很容易:

您的两个用例都在文档中描述

1:检查是否定义了一个值

hstore?文字

因此,对于您的用例

form_values::hstore ? 'a'

2:选择(并比较)值

hstore->文本

因此,对于您的用例

form_values -> product_type 
# this returns '1'

3:将它们添加到查询中:

SELECT * FROM widgets
WHERE form_values::hstore ? 'a'
AND (form_values -> a)::integer = 1

您还可以将其部分包裹在Activerecord中:

Widget.where(
  form_values::hstore ? 'a' 
  AND (form_values -> a)::integer = 1
)

* :: Integer 将字符串值铸成整数。当查询a > 2

的记录时,这将派上用场。

最新更新