package model import ( "apsClient/pkg/snowflake" "encoding/json" "github.com/jinzhu/gorm" "strconv" "time" ) type CommonModel struct { ID uint `gorm:"primary_key" json:"-"` IDStr string `json:"ID" gorm:"-"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` } func (c *CommonModel) BeforeCreate(db *gorm.DB) { if c.ID == 0 { id := snowflake.GenerateID() if id < 0 { // 处理 ID 为负数的情况(可选) id = snowflake.GenerateID() } c.ID = uint(id) } } func (c *CommonModel) UnmarshalJSON(b []byte) error { var data map[string]interface{} if err := json.Unmarshal(b, &data); err != nil { return err } if idStr, ok := data["ID"].(string); ok { id, err := strconv.ParseUint(idStr, 10, 64) if err != nil { return err } c.ID = uint(id) c.IDStr = idStr } return nil } func (c *CommonModel) MarshalJSON() ([]byte, error) { if c.ID != 0 && c.IDStr == "" { c.IDStr = strconv.FormatUint(uint64(c.ID), 10) } return json.Marshal(c) }