go - 如何在 GORM 中定义日期
问题描述
看起来 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"`
}
因此创建的表将具有 TIMESTAMP 作为类型。有没有解决的办法?我试过 sql:"DATE",没用
解决方案
在 Gorm 中使用time.Time
类型进行定义Date
type Header struct {
StartDate time.Time `json:"start_date"`
...
}
数据库表
CREATE TABLE `header` (
...
`start_date` DATE DEFAULT NULL
)
对于解析日期字符串使用这个
format := "2006-01-02"
date, _ := time.Parse(format, "2019-07-10")
为了time.Time
正确处理,您需要parseTime
在连接中包含作为参数。
db, err = Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
更新:
现在我们可以使用GORM Customized Data Types Collection for Date
推荐阅读
- reactjs - 单击时如何仅扩展一个列表项-反应钩子
- scala - 抽象类中未定义类型时出现类型不匹配错误
- php - 在 Laravel 控制器中找不到 PHP 类
- kapt - 如何使用 KotlinPoet 生成地图初始化代码?
- sql - ORA-00920: 具有多个连接并使用最大值的选择子句中的无效关系运算符
- android-studio - SearchView 使用列表视图检索错误数据
- python - 如何使用 python 按字母顺序对 XML 进行排序?
- javascript - 如何根据用户角色禁用或隐藏链接?
- azure - Azure 地图室内模块:如何使用 azure 地图在室内导航中的两点之间绘制路径?
- python - 使用python查看该频道的过滤实时更新