58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
package model
|
|
|
|
import (
|
|
"encoding/json"
|
|
"strings"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
ItemStateOnSale = "onsale"
|
|
ItemStateDelete = "delete"
|
|
)
|
|
|
|
// type 是外部输入的 []int 类型,需要转换成 string 类型存储到数据库
|
|
type ItemModel struct {
|
|
BaseModel
|
|
Itemname string
|
|
Types []int `gorm:"-"`
|
|
TypeString string
|
|
Price int
|
|
Desc string
|
|
Imgs []string `gorm:"-"`
|
|
ImgString string
|
|
State string
|
|
Uid uint
|
|
}
|
|
|
|
func (m *ItemModel) TableName() string {
|
|
return "items"
|
|
}
|
|
func (i *ItemModel) BeforeCreate(tx *gorm.DB) (err error) {
|
|
types_string, _ := json.Marshal(i.Types)
|
|
types := string(types_string)
|
|
i.TypeString = strings.Replace(types, ",", "][", -1)
|
|
|
|
imgs_string, _ := json.Marshal(i.Imgs)
|
|
imgs := string(imgs_string)
|
|
i.ImgString = strings.Replace(imgs, ",", "][", -1)
|
|
return
|
|
}
|
|
|
|
func (i *ItemModel) AfterFind(tx *gorm.DB) (err error) {
|
|
type_string := strings.Replace(i.TypeString, "][", ",", -1)
|
|
err = json.Unmarshal([]byte(type_string), &i.Types)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
img_string := strings.Replace(i.ImgString, "][", ",", -1)
|
|
err = json.Unmarshal([]byte(img_string), &i.Imgs)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|