Gorm模型如何将CrearedAt,UpdatedAt 的值设置为int 时间戳
gorm虽然可以自动帮你维护 created_at、updated_at、deleted_at这些关键时间字段。但是他默认的是 LocalTime 格式,而我们实际开发过程中,可能数据库储存的是int时间戳。
数据表结构体
type Card struct { Model ID uint `gorm:"primary_key" json:"id"` CreatedAt int `json:"created_at"` UpdatedAt int `json:"updated_at"`int }
gorm数据库链接代码
import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "time" ) var Prefix = "pre_" var DB *gorm.DB func Connect() { link := fmt.Sprintf( "%s:%s@tcp(%s:%d)/%s", "username", "password", "127.0.0.1", 3306, "dbname", ) + "?charset=utf8&timeout=10s&readTimeout=60s&writeTimeout=60s&parseTime=True&loc=" + url.QueryEscape("Asia/Shanghai") db, err := gorm.Open("mysql", link) if err != nil { panic(err) } DB = db gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string { return Prefix + defaultTableName } db.Callback().Update().Register("gorm:update_time_stamp", func(scope *gorm.Scope) { if _, ok := scope.Get("gorm:update_column"); !ok { _ = scope.SetColumn("UpdatedAt",time.Now().In(util.Location).Unix()) } }) db.Callback().Create().Register("gorm:update_time_stamp", func(scope *gorm.Scope) { if !scope.HasError() { if createdAtField, ok := scope.FieldByName("CreatedAt"); ok { if createdAtField.IsBlank { _ = createdAtField.Set(time.Now().In(util.Location).Unix()) } } if updatedAtField, ok := scope.FieldByName("UpdatedAt"); ok { if updatedAtField.IsBlank { _ = updatedAtField.Set(time.Now().In(util.Location).Unix()) } } } }) }
基本上就OK了,这样插入个更新数据 created_at,updated_at字段就是时间戳了。