我有一个名为User的记录,其中有一个名为attrs的列。
attrs 是一个 jsonb 列。记录如下所示:
我正在发布as_json
用户的记录。
{
"id"=>uuid1,
"profile_id"=>uuid2,
"campaign_id"=>uuid3,
"asset_id"=>uuid4,
"brand_id"=>"5",
"region"=>"Non-EU",
"attrs"=>{
uuid5=>{
"label"=>"Email",
"value"=>"example@test.com.tw"
},
uuid6=>{
"label"=>"Last Name ",
"value"=>"Yang"
}
}
}
我想查询活动记录User
"label"=>"Email","value"=>"example@test.com.tw"
.
我该怎么做?
尝试,
User.where("settings @> ?", {uuid5: {label: 'Email', value: 'example@test.com.tw'}}.to_json)
有关更多参考,请参阅..
https://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails
感谢a_horse_with_no_name
答案,这里有一个原始的sql版本:
select u.*
from users u
where exists (select *
from jsonb_each(u.attrs) as t(uid,entry)
where t.entry ->> 'label' = 'Email'
and t.entry ->> 'value' = 'example@test.com.tw')
这是AR版本:
User.find_by_sql(["
select u.*
from users u
where exists (select *
from jsonb_each(u.attrs) as t(uid,entry)
where t.entry ->> 'label' = ?
and t.entry ->> 'value' = ?)
", 'Email', 'example@test.com.tw'])
可以将其移动到模型范围或方法。或者分隔查询对象。
它依赖于postgresql jsonb_each
方法。我刚刚注意到您没有指定数据库
参考 https://stackoverflow.com/a/55512200/4950680