To store a list of strings as a JSONB object in Postgres using GORM, a common approach involves utilizing GORM's custom type, postgres.Jsonb. However, to avoid this dependency, here's an alternative solution:
Instead of relying on GORM's specific type, consider implementing pgtype.JSONB from the pgx package, which GORM uses as its driver. Here's how you can incorporate it into your model:
import ( "github.com/jackc/pgx" "github.com/jackc/pgx/pgtype" ) type User struct { gorm.Model Data pgtype.JSONB `gorm:"type:jsonb;default:'[]';not null"` }
Retrieving the actual list of strings from the database:
u := User{} db.Find(&u) var data []string err := u.Data.AssignTo(&data) if err != nil { // Handle error }
Updating the list of strings in the database:
u := User{} err := u.Data.Set([]string{"abc", "def"}) if err != nil { // Handle error } db.Updates(&u)
By leveraging pgtype.JSONB, you can manipulate JSONB data within your Go models without using GORM's postgres.Jsonb type, providing a more direct and flexible approach to working with JSONB in Postgres.
The above is the detailed content of How to Efficiently Manage JSONB []string Data in GORM without postgres.Jsonb?. For more information, please follow other related articles on the PHP Chinese website!