YiTao/model/item_model.go

58 lines
1.2 KiB
Go
Raw Normal View History

2024-11-09 14:59:27 +08:00
package model
import (
"encoding/json"
2024-11-09 21:24:02 +08:00
"strings"
2024-11-09 14:59:27 +08:00
"gorm.io/gorm"
)
const (
ItemStateOnSale = "onsale"
2024-11-09 16:36:28 +08:00
ItemStateDelete = "delete"
2024-11-09 14:59:27 +08:00
)
// type 是外部输入的 []int 类型,需要转换成 string 类型存储到数据库
type ItemModel struct {
BaseModel
Itemname string
Types []int `gorm:"-"`
TypeString string
Price int
Desc string
2024-11-21 21:52:35 +08:00
Imgs []string `gorm:"-"`
ImgString string
2024-11-09 16:36:28 +08:00
State string
Uid uint
2024-11-09 14:59:27 +08:00
}
func (m *ItemModel) TableName() string {
return "items"
}
func (i *ItemModel) BeforeCreate(tx *gorm.DB) (err error) {
types_string, _ := json.Marshal(i.Types)
2024-11-09 21:24:02 +08:00
types := string(types_string)
i.TypeString = strings.Replace(types, ",", "][", -1)
2024-11-21 21:52:35 +08:00
imgs_string, _ := json.Marshal(i.Imgs)
imgs := string(imgs_string)
i.ImgString = strings.Replace(imgs, ",", "][", -1)
2024-11-09 14:59:27 +08:00
return
}
func (i *ItemModel) AfterFind(tx *gorm.DB) (err error) {
2024-11-09 21:24:02 +08:00
type_string := strings.Replace(i.TypeString, "][", ",", -1)
err = json.Unmarshal([]byte(type_string), &i.Types)
2024-11-21 21:52:35 +08:00
if err != nil {
return
}
img_string := strings.Replace(i.ImgString, "][", ",", -1)
err = json.Unmarshal([]byte(img_string), &i.Imgs)
if err != nil {
return
}
2024-11-09 14:59:27 +08:00
return
}