定義模型
type ProgramModel struct {
gorm.Model
Name string `json:"name" gorm:"column:name"`
StartTime string `json:"start_time" gorm:"column:start_time"`
EndTime string `json:"end_time" gorm:"column:end_time"`
}
其中gorm.Model
內容如下
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
}
ProgramModel
的StartTime
、EndTime
、CreatedAt
、UpdatedAt
、DeletedAt
在數據庫中是datetime
類型,但是輸出卻是2019-08-09T11:35:52+08:00
,如果希望得到2019-08-09 11:35:52
這種輸出怎么辦呢?
解決CreatedAt
、UpdatedAt
、DeletedAt
輸出
官方github的Issuse中有類似問題參考鏈接,使用自定義結構BaseModel
代替gorm.Model
type ProgramModel struct {
BaseModel
Name string `json:"name" gorm:"column:name"`
StartTime BaseModel `json:"start_time" gorm:"column:start_time"`
EndTime BaseModel `json:"end_time" gorm:"column:end_time"`
}
type BaseModel struct {
gorm.Model
Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"id"`
CreatedAt MyTime `gorm:"column:create_time" json:"create_time"`
UpdatedAt MyTime `gorm:"column:update_time" json:"update_time"`
}
type MyTime struct {
time.Time
}
func (t MyTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", t.Format(timeFormat))
return []byte(formatted), nil
}
func (t MyTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
func (t *MyTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = MyTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
這樣解決了CreatedAt
、UpdatedAt
、DeletedAt
的問題。
但是使用類似
testStr := `{
"name": "test",
"start_time": "2019-08-09 10:00:23",
"end_time": "2019-08-09 11:00:23"
}`
var obj ProgramModel
if err := json.Unmarshal([]byte(testStr), &obj); err != nil {
panic(err)
}
來創建數據時候卻不行,我又不想再定義一個結構體接收之后在后轉換
解決StartTime、EndTime的輸出
修改配置
去掉鏈接數據庫配置的parseTime=%t&loc=%s
;最后就是
config := fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8",
username,
password,
addr,
port,
name)
將所有時間字段全部改為string
類型。如下
type BaseModel struct {
gorm.Model
Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"id"`
CreatedAt string `gorm:"column:create_time" json:"create_time"`
UpdatedAt string `gorm:"column:update_time" json:"update_time"`
}
type ProgramModel struct {
BaseModel
Name string `json:"name" gorm:"column:name"`
StartTime string `json:"start_time" gorm:"column:start_time"`
EndTime string `json:"end_time" gorm:"column:end_time"`
}
這樣就就可以了,但是UpdatedAt
這個字段無法自動更新。可以添加如下方法,這樣每次更新時候都會調用該方法
func (v BaseModel) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("create_time", NowTime())
scope.SetColumn("update_time", NowTime())
return nil
}
func (v BaseModel) BeforeUpdate(scope *gorm.Scope) error {
scope.SetColumn("update_time", NowTime())
return nil
}
關於 gorm的parseTime和loc
parseTime是自動轉換為時間
go
使用RFC3339Nano
這個格式來Marshal
時間
// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
func (t Time) MarshalJSON() ([]byte, error) {
if y := t.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
b := make([]byte, 0, len(RFC3339Nano)+2)
b = append(b, '"')
b = t.AppendFormat(b, RFC3339Nano)
b = append(b, '"')
return b, nil
}
所以才有上面自定義類型,自定義MarshalJSON
方法。
loc
是 MySQL的時區設置
mysql> show variables like "%time_zone%";
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | CST |
| time_zone | SYSTEM |
+------------------+--------+
2 rows in set (0.04 sec)
time_zone
說明mysql使用system的時區;system_time_zone
說明system使用CST時區