package base import ( "encoding/json" "github.com/google/uuid" "gorm.io/gorm" "time" ) type Model struct { ID int64 `gorm:"type:bigint;primaryKey;autoIncrement" json:"id"` Key string `gorm:"type:varchar(50);uniqueIndex" json:"key"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"` } func (m *Model) Delete() { m.DeletedAt.Time = time.Now() m.DeletedAt.Valid = true } func (m *Model) MarshalBinary() ([]byte, error) { return json.Marshal(m) } func (m *Model) UnmarshalBinary(data []byte) error { return json.Unmarshal(data, m) } // BeforeCreate 钩子在创建记录之前执行 func (m *Model) BeforeCreate(tx *gorm.DB) (err error) { if m.Key == "" { m.Key = uuid.New().String() // 使用 UUID 作为默认值 } return }