91 lines
2.4 KiB
Go
91 lines
2.4 KiB
Go
package models
|
|
|
|
import (
|
|
"github.com/jinzhu/gorm"
|
|
"time"
|
|
)
|
|
|
|
var RecordNotFound = gorm.ErrRecordNotFound
|
|
|
|
type BaseModel struct {
|
|
CreatedAt time.Time `json:"createdAt"` // 创建时间
|
|
UpdatedAt time.Time `json:"updatedAt"` // 更新时间
|
|
DeletedAt *time.Time `json:"deletedAt"` // 删除时间
|
|
}
|
|
|
|
type Model struct {
|
|
ID uint32 `json:"id" gorm:"primary_key;AUTO_INCREMENT"` // 数据库记录编号
|
|
CreatedAt time.Time `json:"createdAt"` // 创建时间
|
|
UpdatedAt time.Time `json:"-"` // 更新时间
|
|
DeletedAt *time.Time `json:"-" sql:"index"` // 删除时间
|
|
}
|
|
|
|
type Unix struct {
|
|
ID uint32 `gorm:"primary_key"`
|
|
Created time.Time `gorm:"-"` // 忽略储存在数据库
|
|
CreatedUnix int64
|
|
Updated time.Time `gorm:"-"` // 忽略储存在数据库
|
|
UpdatedUnix int64
|
|
}
|
|
|
|
// 查询前把时间格式化
|
|
func (m *Unix) AfterFind() (err error) {
|
|
m.Created = time.Unix(m.CreatedUnix, 0).Local()
|
|
m.Updated = time.Unix(m.UpdatedUnix, 0).Local()
|
|
return
|
|
}
|
|
|
|
// 更新前对时间戳创建
|
|
func (m *Unix) BeforeCreate() (err error) {
|
|
m.UpdatedUnix = time.Now().Local().Unix()
|
|
m.CreatedUnix = time.Now().Local().Unix()
|
|
return
|
|
}
|
|
|
|
// 更新前对时间戳更改
|
|
func (m *Unix) BeforeUpdate(scope *gorm.Scope) (err error) {
|
|
return scope.SetColumn("UpdatedUnix", time.Now().Local().Unix())
|
|
}
|
|
|
|
type Unix64 struct {
|
|
ID uint64 `gorm:"primary_key"`
|
|
Created time.Time `gorm:"-"` // 忽略储存在数据库
|
|
CreatedUnix int64
|
|
Updated time.Time `gorm:"-"` // 忽略储存在数据库
|
|
UpdatedUnix int64
|
|
}
|
|
|
|
// 查询前把时间格式化
|
|
func (m *Unix64) AfterFind() (err error) {
|
|
m.Created = time.Unix(m.CreatedUnix, 0).Local()
|
|
m.Updated = time.Unix(m.UpdatedUnix, 0).Local()
|
|
return
|
|
}
|
|
|
|
// 更新前对时间戳创建
|
|
func (m *Unix64) BeforeCreate() {
|
|
m.UpdatedUnix = time.Now().Local().Unix()
|
|
m.CreatedUnix = time.Now().Local().Unix()
|
|
}
|
|
|
|
// 更新前对时间戳更改
|
|
func (m *Unix64) BeforeUpdate(scope *gorm.Scope) (err error) {
|
|
return scope.SetColumn("UpdatedUnix", time.Now().Local().Unix())
|
|
}
|
|
|
|
type Deleted struct {
|
|
Unix64
|
|
DeletedUnix int64 `sql:"index"`
|
|
}
|
|
|
|
// 删除回调
|
|
func (d *Deleted) BeforeCreate() {
|
|
d.Unix64.BeforeCreate()
|
|
d.DeletedUnix = -1
|
|
}
|
|
|
|
// 执行删除操作
|
|
func (d *Deleted) BeforeDelete(scope *gorm.Scope) (err error) {
|
|
return scope.SetColumn("DeletedUnix", time.Now().Local().Unix())
|
|
}
|