官方json文档 https://www.postgresql.org/docs/12/functions-json.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package main
import ( "database/sql/driver" "encoding/json" "fmt" "gorm.io/driver/postgres" "gorm.io/gorm" )
var db *gorm.DB
func initPgsql() { dsn := "host=192.168.163.121 user=postgres password=postgres dbname=test port=5432 sslmode=disable TimeZone=Asia/Shanghai" var err error db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { panic(err) } }
type User struct { gorm.Model Name string Profile Profile `gorm:"type:json" json:"profile"` }
type Profile struct { Email string `json:"email"` PhoneNo string `json:"phoneNo"` }
func (p Profile) Value() (driver.Value, error) { return json.Marshal(p) }
func (p *Profile) Scan(input interface{}) error { return json.Unmarshal(input.([]byte), p) }
func main() { initPgsql() err := db.AutoMigrate(&User{}) if err != nil { panic(err) } u := User{ Name: "maocat", Profile: Profile{ Email: "maocatooo@gmail.com", PhoneNo: "18888888888", }, } db.Save(&u)
u.Profile.PhoneNo = "13666666666" db.Save(&u)
var u1 User
db.Debug(). Where(gorm.Expr("profile->>'email' = ?", "maocatooo@gmail.com")). First(&u1) fmt.Println(u1.Name) fmt.Println(u1.Profile) }
|