refactor(database): 重构数据库基础模型时间类型

- 将 LocalTime 类型重命名为 DateTime 并改进实现
- 添加完整的 JSON 序列化和反序列化支持
- 实现了 MarshalJSON 和 UnmarshalJSON 方法
- 改进 Scan 方法以支持字符串类型转换
- 更新 BaseModel 结构体字段定义和标签
- 移除指针类型改为值类型并优化 GORM 标签配置
main v1.0.1025
maguodong 2026-03-28 15:58:46 +08:00
parent 93fbb99ee0
commit 21e9f7c79d
1 changed files with 42 additions and 13 deletions

View File

@ -2,31 +2,53 @@ package model
import ( import (
"database/sql/driver" "database/sql/driver"
"encoding/json"
"fmt" "fmt"
"time" "time"
) )
// LocalTime 自定义时间类型,支持 null 值 // DateTime 自定义时间类型
type LocalTime struct { type DateTime struct {
time.Time time.Time
} }
func (t *LocalTime) MarshalJSON() ([]byte, error) { // MarshalJSON 实现 JSON 序列化
if t == nil || t.IsZero() { func (t DateTime) MarshalJSON() ([]byte, error) {
if t.IsZero() {
return []byte("null"), nil return []byte("null"), nil
} }
formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05")) return json.Marshal(t.Format("2006-01-02 15:04:05"))
return []byte(formatted), nil
} }
func (t *LocalTime) Value() (driver.Value, error) { // UnmarshalJSON 实现 JSON 反序列化
if t == nil || t.IsZero() { func (t *DateTime) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if s == "" || s == "null" {
t.Time = time.Time{}
return nil
}
parsed, err := time.Parse("2006-01-02 15:04:05", s)
if err != nil {
return err
}
t.Time = parsed
return nil
}
// Value 实现 driver.Valuer
func (t DateTime) Value() (driver.Value, error) {
if t.IsZero() {
return nil, nil return nil, nil
} }
return t.Time, nil return t.Time, nil
} }
func (t *LocalTime) Scan(v interface{}) error { // Scan 实现 sql.Scanner
func (t *DateTime) Scan(v interface{}) error {
if v == nil { if v == nil {
t.Time = time.Time{} t.Time = time.Time{}
return nil return nil
@ -36,14 +58,21 @@ func (t *LocalTime) Scan(v interface{}) error {
case time.Time: case time.Time:
t.Time = value t.Time = value
return nil return nil
case string:
parsed, err := time.Parse("2006-01-02 15:04:05", value)
if err != nil {
return err
}
t.Time = parsed
return nil
default: default:
return fmt.Errorf("unsupported type: %T", v) return fmt.Errorf("unsupported type: %T", v)
} }
} }
// BaseModel 基础模型,包含自定义的创建时间和更新时间 // 基础模型
type BaseModel struct { type BaseModel struct {
Id int `json:"id" gorm:"column:id;primaryKey;autoIncrement;common:主键ID"` // 主键 ID ID uint `gorm:"column:id;primaryKey;autoIncrement;common:主键ID" json:"id"`
CreateTime *LocalTime `json:"create_time" gorm:"column:create_time;type:datetime;autoCreateTime;common:创建时间"` CreateTime DateTime `gorm:"autoCreateTime;column:create_time;type:datetime" json:"create_time"`
UpdateTime *LocalTime `json:"update_time" gorm:"column:update_time;type:datetime;autoUpdateTime;common:更新时间"` UpdateTime DateTime `gorm:"autoUpdateTime;column:update_time;type:datetime" json:"update_time"`
} }