feat(database): 添加自定义时间类型支持空值

- 新增 LocalTime 自定义时间类型,支持 null 值处理
- 实现 MarshalJSON 方法支持 JSON 序列化
- 实现 Value 方法支持数据库存储
- 实现 Scan 方法支持数据库读取
- 修改 BaseModel 使用 LocalTime 类型替代原生 time.Time
- 移除 BaseModel 中的时间处理钩子函数
main v1.0.1024
maguodong 2026-03-28 15:52:33 +08:00
parent d41b554acf
commit 93fbb99ee0
1 changed files with 40 additions and 24 deletions

View File

@ -1,33 +1,49 @@
package model package model
import ( import (
"database/sql/driver"
"fmt"
"time" "time"
"gorm.io/gorm"
) )
// LocalTime 自定义时间类型,支持 null 值
type LocalTime struct {
time.Time
}
func (t *LocalTime) MarshalJSON() ([]byte, error) {
if t == nil || t.IsZero() {
return []byte("null"), nil
}
formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
return []byte(formatted), nil
}
func (t *LocalTime) Value() (driver.Value, error) {
if t == nil || t.IsZero() {
return nil, nil
}
return t.Time, nil
}
func (t *LocalTime) Scan(v interface{}) error {
if v == nil {
t.Time = time.Time{}
return nil
}
switch value := v.(type) {
case time.Time:
t.Time = value
return nil
default:
return fmt.Errorf("unsupported type: %T", v)
}
}
// BaseModel 基础模型,包含自定义的创建时间和更新时间 // BaseModel 基础模型,包含自定义的创建时间和更新时间
type BaseModel struct { type BaseModel struct {
Id int `json:"id" gorm:"column:id;primaryKey;autoIncrement;common:主键ID"` // 主键 ID Id int `json:"id" gorm:"column:id;primaryKey;autoIncrement;common:主键ID"` // 主键 ID
CreateTime time.Time `json:"create_time" gorm:"column:create_time;type:datetime;autoCreateTime;common:创建时间"` CreateTime *LocalTime `json:"create_time" gorm:"column:create_time;type:datetime;autoCreateTime;common:创建时间"`
UpdateTime time.Time `json:"update_time" gorm:"column:update_time;type:datetime;autoUpdateTime;common:更新时间"` UpdateTime *LocalTime `json:"update_time" gorm:"column:update_time;type:datetime;autoUpdateTime;common:更新时间"`
}
// 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
}
func (b *BaseModel) AfterFind(tx *gorm.DB) error {
b.UpdateTime = time.Now()
return nil
} }