【发布时间】:2021-09-06 21:27:15
【问题描述】:
我有一张像下面这样的表格
INSERT INTO switches VALUES ('33', 60, jsonb_build_object('IDs',jsonb_build_array('11', '2'),'ID', '33', 'Name', 'switch1'));
我有一个结构/模型
type switches struct {
ID string `gorm:"primary_key; unique; json:id"`
Generation uint32 `gorm:"type:integer; column:generation;" json:"generation" `
// Additional gorm type jsonb set, if not present causes field to be bytea
SwitchAttrs []byte `sql:"type:jsonb; not null; column:Switch_attrs;" gorm:"type:jsonb; json:switchAttrs"`
}
我可以在 postgres 中查询
SELECT * FROM switches WHERE switch_attrs->'IDs' ? '2'
id | generation | data
----+-------+------------------
33 | 60 | {"IDs": ["33","2"] }
如何针对特定键在 jsonB 列上构造查询?我找不到任何使用模型对象进行查询的文档,其中解释了如何使用“in”运算符。我了解它可能与原始查询有关,但想看看如何使用模型对象来完成。我正在尝试进行如下查询,但失败了:(
db = db.Where("Switch_attrs->'IDs' ?", "2").Find(&switches)
或
db = db.Where("Switch_attrs->'IDs' ?", []string{"2"}).Find(&switches)
或
db = db.Where("Switch_attrs->'IDs' IN ?", []string{"2"}).Find(&switches)
或
db = db.Where("Switch_attrs->>'IDs' ?", "2").Find(&switches) . Note that i am querying as switch_attrs->>'IDs' . i expect the o/p as text and hence passing the value as "2".
对于最后一个查询,我不断收到错误
“严重性”:“错误”,“代码”:“42601”,“消息”:“语法错误 或“$1”附近,
【问题讨论】: