英文:
Gorm Timestamps in Golang
问题
type Base struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *gorm.DeletedAt `sql:"index" json:"deleted_at" swaggertype:"primitive,string"`
CreatedByID uint `gorm:"column:created_by_id" json:"created_by_id"`
UpdatedByID uint `gorm:"column:updated_by_id" json:"updated_by_id"`
}
如果我传递一些值给created_at
和updated_at
,它会将当前时间作为默认值,而不是使用我传递的值。有没有办法让gorm使用我传递的值?
英文:
type Base struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *gorm.DeletedAt `sql:"index" json:"deleted_at" swaggertype:"primitive,string"`
CreatedByID uint `gorm:"column:created_by_id" json:"created_by_id"`
UpdatedByID uint `gorm:"column:updated_by_id" json:"updated_by_id"`
}
If I pass some values to created_at and updated_at it is taking up the current time as a default value and not taking up the value that I have passed. Is there any way I can make the gorm take up the values that I have passed.
答案1
得分: 7
三种方法
- 为具有数据库函数的字段定义默认标签,以填充默认值。例如,对于MySQL数据库,可以使用
current_timestamp()
。
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP()"`
- 根据@Guolei的建议,分配默认值。
- 在结构体中嵌入
gorm.Model
,以自动处理ID、CreatedAt、UpdatedAt和DeletedAt。
英文:
Three ways
- Define default tag for field with a database function to fill in the default. e.g. for MySQL database
current_timestamp()
can be used
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP()"`
- Assign default values as suggested by @Guolei.
- Embed
gorm.Model
in your struct instead, for automatic handling of ID, CreatedAt, UpdatedAt and DeletedAt.
答案2
得分: 1
如果包含字段:CreatedAt和UpdatedAt,gorm在执行时将使用反射插入默认值。你也可以给出具体的值。
info := Example{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
_, err := DB.Insert(info)
英文:
if containing fileds: CreatedAt and UpdatedAt, gorm will use reflect to insert default value when executing.
also you could give the specific value.
info := Example{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
_, err := DB.Insert(info)
答案3
得分: 1
@s3vt的答案更新:
如果你使用他们提供的第一种方法,你需要将函数放在括号之外,像这样:
CreatedAt time.Time `gorm:"default:current_timestamp"`
我花了很多时间来解决我遇到的错误,所以我想与可能遇到这个问题的人分享一下!
英文:
An update to @s3vt's answer:
If you the first method they provided, you need to put the function without the parenthesis like this:
CreatedAt time.Time `gorm:"default:current_timestamp"`
I spent a lot of time trying to figure out the error I was getting so I thought I'd share it for the people who might face this!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论