Files
sundynix-micro-be/common/model/base_model.go
T
2026-05-24 01:41:22 +08:00

41 lines
1.1 KiB
Go

package model
import (
"sundynix-micro-go/common/utils/uniqueid"
"time"
"gorm.io/gorm"
)
// BaseModel 基础模型,所有表的公共字段
type BaseModel struct {
ID string `gorm:"size:50;primaryKey" json:"id"`
CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updatedAt" gorm:"autoCreateTime;autoUpdateTime"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
CreatedAtStr string `gorm:"-" json:"createdAtStr"`
}
// BeforeCreate 创建前自动生成雪花ID
func (m *BaseModel) BeforeCreate(db *gorm.DB) (err error) {
if m.ID == "" {
m.ID = uniqueid.GenerateID()
}
db.Statement.SetColumn("id", m.ID)
return
}
// BeforeUpdate 更新前自动更新时间
func (m *BaseModel) BeforeUpdate(db *gorm.DB) (err error) {
db.Statement.SetColumn("updated_at", time.Now())
return
}
// AfterFind 查询后自动填充 createdAtStr
func (m *BaseModel) AfterFind(db *gorm.DB) (err error) {
if !m.CreatedAt.IsZero() {
m.CreatedAtStr = m.CreatedAt.Format("2006-01-02 15:04:05")
}
return
}