Skip to content

Instantly share code, notes, and snippets.

@encryptblockr
Forked from yanmhlv/example.go
Created August 7, 2022 19:08
Show Gist options
  • Save encryptblockr/2f0cf65e313d9ab22242da0ffc90995b to your computer and use it in GitHub Desktop.
Save encryptblockr/2f0cf65e313d9ab22242da0ffc90995b to your computer and use it in GitHub Desktop.

Revisions

  1. @yanmhlv yanmhlv revised this gist Feb 8, 2016. 1 changed file with 1 addition and 9 deletions.
    10 changes: 1 addition & 9 deletions example.go
    Original file line number Diff line number Diff line change
    @@ -31,13 +31,5 @@ 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",
    },
    },
    )
    db.Create(&User{Info: JSONB{"age": 27, "name": "Yan"}})
    }
  2. @yanmhlv yanmhlv created this gist Feb 8, 2016.
    43 changes: 43 additions & 0 deletions example.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    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",
    },
    },
    )
    }