Skip to content

Instantly share code, notes, and snippets.

@gate3
Forked from yanmhlv/example.go
Created August 5, 2022 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gate3/5744e6fc7d49c8b492beead98621b1ca to your computer and use it in GitHub Desktop.
Save gate3/5744e6fc7d49c8b492beead98621b1ca to your computer and use it in GitHub Desktop.
JSONB in gorm
package main
import (
"database/sql/driver"
"encoding/json"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type JSONB map[string]interface{}
func (j JSONB) Value() (driver.Value, error) {
valueString, err := json.Marshal(j)
return string(valueString), err
}
func (j *JSONB) Scan(value interface{}) error {
if err := json.Unmarshal(value.([]byte), &j); err != nil {
return err
}
return nil
}
type User struct {
gorm.Model
Info JSONB `sql:"type:jsonb"`
}
func main() {
db, _ := gorm.Open("postgres", "user=myuser password=mypassword dbname=mydbname sslmode=disable")
db.CreateTable(&User{})
db.Create(&User{Info: JSONB{"age": 27, "name": "Yan"}})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment