Your Question
How do you properly select a row by a JSONSlice column with @> operator? I have the following code:
type Destination struct {
ID string `json:"id"`
Client string `json:"client"`
}
type Account struct {
ID uuid.UUID `json:"id" gorm:"type:uuid;default:uuid_generate_v4()"`
Destination datatypes.JSONSlice[Destination] `json:"destination" gorm:"index;not null;type:json"`
Emails pq.StringArray `json:"emails" gorm:"index;type:text[]"`
}
And I want to select an account, that has destination.id = "123456789". But it seems that GORM does not have the option to parse maps as pgsql wants ([{"id":"123456789"}]). Instead, it parses maps as map[id:123456789].
I've tried the following methods:
var result Account
response := db.Where(`destination @> ?`, map[string]interface{}{"id": id}).First(&result) // Returns SELECT * FROM "accounts" WHERE destination @> 'map[id:5187696616]' therefore map doesn't even exists as a token in postgre
var result Account
response := db.Where(`destination @> '[ { "id": ? }]'`, id).Find(&result) // Returns SELECT * FROM "accounts" WHERE destination @> '[ { "id": '1234567890' }]' placing ' ' before and after the ID.
var result Account
response := db.Raw(`SELECT * FROM accounts WHERE destination @> '[ { "id": ? }]'`, id).Find(&result) // Also placing the ' ' before and after
So, what is the correct way to handle this?
The document you expected this should be explained
Expected answer
The correct way to handle this in GORM.
Comment From: Romankrasawa
it seems to me that somewhere there is an problem
Comment From: kyee-rs
Fixed with datatypes.JSONSlice type
db.Where("destination @> ?", datatypes.JSONSlice[map[string]interface{}]{{"id": id}})