package main
import (
"encoding/json"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/pkg/errors"
)
// 商品
type Product struct {
Id int `gorm:"primary_key"`
Name string `gorm:"not null"`
UserId int `gorm:"not null"`
Spec string `gorm:"not null"` //{"Spec":["dongTech","product"]}
MutiSpec *Spec
}
type Spec struct {
Spec []string //多个标签
}
func GetDB() *gorm.DB {
db, err := gorm.Open("postgres", "postgres://postgres:root@localhost:5432/test?sslmode=disable")
if err != nil {
fmt.Println("db error:", err)
} else {
fmt.Println("database connection success")
}
//defer db.Close()
return db
}
func (p *Spec) Json2String() (string, error) {
bs, err := json.Marshal(p)
return string(bs), errors.WithStack(err)
}
func (p *Product) string2Json() (*Spec, error) {
var spec Spec
err := json.Unmarshal([]byte(p.Spec), &spec)
return &spec, errors.WithStack(err)
}
func main() {
db := GetDB()
models := []interface{}{
&Product{},
}
//1.执行建表语句
err := db.Debug().AutoMigrate(models...).Error
if err != nil {
fmt.Println("db error:", err)
}
//2.创建一个商品
err = CreateProduct(db, 1, 1, "dongTech", &Spec{Spec: []string{"dongTech", "product"}})
if err != nil {
fmt.Println("create product error:", err)
}
//3.获取商品
product, err := GetProduct(db, 1)
if err != nil {
fmt.Println("get product error:", err)
}
fmt.Println(product)
}
func CreateProduct(db *gorm.DB, id, userId int, name string, MutiSpec *Spec) error {
spec, err := MutiSpec.Json2String()
if err != nil {
return err
}
product := &Product{
Id: id,
UserId: userId,
Name: name,
Spec: spec,
}
err = db.Debug().Create(product).Error
if err != nil {
return err
}
fmt.Println("create product success")
return nil
}
func GetProduct(db *gorm.DB, id int) (*Product, error) {
var product Product
err := db.Debug().Model(&product).Where("id = ?", id).Scan(&product).Error
if err != nil {
return nil, err
}
mutiSpec, err := product.string2Json()
if err != nil {
return nil, err
}
product.MutiSpec = mutiSpec
return &product, nil
}
复制代码
数据库:
运行结果:
|