feat(database): 添加基础数据模型

- 创建 BaseModel 结构体,包含主键 ID、创建时间和更新时间字段
- 实现 BeforeCreate 钩子函数,自动设置创建和更新时间为当前时间
- 实现 BeforeUpdate 钩子函数,自动更新更新时间为当前时间
- 配置 GORM 数据库映射标签,包括主键、列名、数据类型等
- 添加 JSON 序列化标签支持,便于 API 返回数据
main
maguodong 2026-03-28 14:36:43 +08:00
parent 3209cfe830
commit 80ad00f98d
1 changed files with 28 additions and 0 deletions

28
database/model/base.go Normal file
View File

@ -0,0 +1,28 @@
package model
import (
"time"
"gorm.io/gorm"
)
// BaseModel 基础模型,包含自定义的创建时间和更新时间
type BaseModel struct {
Id int `json:"id" gorm:"column:id;primaryKey;autoIncrement;common:主键ID"` // 主键 ID
CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"created_at"` // 创建时间
UpdateTime time.Time `gorm:"column:update_time;type:datetime;not null" json:"updated_at"` // 更新时间
}
// BeforeCreate 创建前自动设置时间
func (b *BaseModel) BeforeCreate(tx *gorm.DB) error {
now := time.Now()
b.CreateTime = now
b.UpdateTime = now
return nil
}
// BeforeUpdate 更新前自动更新时间
func (b *BaseModel) BeforeUpdate(tx *gorm.DB) error {
b.UpdateTime = time.Now()
return nil
}