Home > Backend Development > Golang > How to Efficiently Manage JSONB []string Data in GORM without postgres.Jsonb?

How to Efficiently Manage JSONB []string Data in GORM without postgres.Jsonb?

Barbara Streisand
Release: 2024-11-26 08:55:10
Original
837 people have browsed it

How to Efficiently Manage JSONB []string Data in GORM without postgres.Jsonb?

Manipulating JSONB in Gorm with a []string

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:

Using pgtype.JSONB

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"`
}
Copy after login

Working with pgtype.JSONB

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
}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template