GORM 字段自动更新时间
时间: 2023-07-10 20:05:41 浏览: 71
在 GORM 中,可以使用 `BeforeSave` 和 `BeforeUpdate` 钩子函数来自动更新字段时间。具体实现如下:
```go
import (
"time"
"gorm.io/gorm"
)
type User struct {
gorm.Model
Name string
CreatedAt time.Time
UpdatedAt time.Time
}
func (u *User) BeforeSave(tx *gorm.DB) (err error) {
if u.ID == 0 {
u.CreatedAt = time.Now()
}
u.UpdatedAt = time.Now()
return nil
}
```
在上面的例子中,定义了一个 `User` 结构体,其中包含了 `CreatedAt` 和 `UpdatedAt` 字段。在 `BeforeSave` 函数中,通过判断 `ID` 是否为 0 来判断是否为新数据,如果是新数据,则更新 `CreatedAt` 字段,否则更新 `UpdatedAt` 字段。
需要注意的是,`BeforeSave` 和 `BeforeUpdate` 钩子函数的返回值类型必须为 `error`,如果没有错误则返回 `nil`。
相关问题
GORM 字段标签自动更新时间
在 GORM 中,我们可以使用字段标签来指定数据库表的字段名、类型、约束等信息。如果我们想要在模型中定义一个字段,在数据插入或更新时自动更新时间,我们可以使用 `gorm:"autoUpdateTime"` 标签。
下面是一个示例模型:
```go
type User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"not null"`
Email string `gorm:"unique"`
CreatedAt time.Time
UpdatedAt time.Time `gorm:"autoUpdateTime"`
}
```
在上面的模型中,`UpdatedAt` 字段使用了 `gorm:"autoUpdateTime"` 标签。这意味着在每次更新该模型时,GORM 会自动将 `UpdatedAt` 字段设置为当前时间。
当我们使用 GORM 更新模型时,只需要更新相应的字段即可。例如:
```go
user := User{Name: "John", Email: "john@example.com"}
db.Create(&user)
// 更新用户的邮箱
db.Model(&user).Update("Email", "new.email@example.com")
// 更新用户的名称和邮箱
db.Model(&user).Updates(User{Name: "John Doe", Email: "johndoe@example.com"})
```
在上面的代码中,每次更新模型时,`UpdatedAt` 字段都会自动更新为当前时间。
需要注意的是,`gorm:"autoUpdateTime"` 标签只能用于 `time.Time` 类型的字段。如果我们要更新其他类型的字段,可以自定义 GORM 的回调函数来实现。
gorm新增时间字段不填充_Gorm使用心得,那些你可能会踩到的坑。
在使用 Gorm 进行新增操作时,如果你在数据模型中定义了时间字段,但是在新增时没有传入时间值,那么 Gorm 会自动填充当前时间。如果你不想让 Gorm 自动填充时间字段,可以在定义模型时指定时间字段的类型为 `*time.Time`,然后在新增数据时将时间字段的值设置为 `nil`。
示例代码如下:
```go
type User struct {
ID uint `gorm:"primary_key"`
Name string `gorm:"not null"`
CreatedAt *time.Time `gorm:"index"`
}
// 新增用户,不填充 CreatedAt 字段
user := User{Name: "test"}
db.Create(&user)
```
注意,如果你在定义模型时使用了 `time.Time` 类型而不是 `*time.Time` 类型,那么 Gorm 会自动填充时间字段,即使你在新增时没有传入时间值。