看起来 GORM 不支持 DATE 类型,定义日期的唯一方法是通过 time.Time :
type Header struct {
Start time.Time `json:"period_start"`
End time.Time `json:"period_end" `
CreatedAt time.Time `json:"created_at" sql:"DEFAULT:CURRENT_TIMESTAMP"`
CreatedBy string `json:"created_by"`
UpdatedAt time.Time `json:"updated_at" sql:"DEFAULT:CURRENT_TIMESTAMP"`
UpdatedBy string `json:"updated_by"`
}
Run Code Online (Sandbox Code Playgroud)
因此创建的表将以 TIMESTAMP 作为类型。有没有解决的办法?我尝试了 sql:"DATE",但没有成功
Ekl*_*vya 11
在 Gorm 中使用time.Time类型进行定义Date
type Header struct {
StartDate time.Time `json:"start_date"`
...
}
Run Code Online (Sandbox Code Playgroud)
数据库表
CREATE TABLE `header` (
...
`start_date` DATE DEFAULT NULL
)
Run Code Online (Sandbox Code Playgroud)
要解析日期字符串,请使用此
format := "2006-01-02"
date, _ := time.Parse(format, "2019-07-10")
Run Code Online (Sandbox Code Playgroud)
为了time.Time正确处理,您需要将其parseTime作为参数包含在连接中。
db, err = Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
Run Code Online (Sandbox Code Playgroud)
更新:
现在我们可以使用GORM 自定义日期数据类型集合