GORM DATETIME个十年
时间: 2023-10-01 16:11:28 浏览: 51
GORM是一个Go语言的ORM库,它支持多种数据库系统,包括MySQL、PostgreSQL、SQLite等。如果你要使用GORM来操作MySQL数据库中的DATETIME类型字段,你可以按照以下方式定义模型:
```go
import (
"time"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"size:255"`
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
DeletedAt gorm.DeletedAt `gorm:"index"`
// 其他字段
}
```
在这个模型中,CreatedAt和UpdatedAt字段都是GORM默认添加的字段,用于记录数据的创建时间和更新时间。它们的数据类型是time.Time,对应MySQL中的DATETIME类型。如果你需要将模型中的时间字段值设置为当前时间,你可以在创建记录时使用time.Now()函数来设置:
```go
user := User{
Name: "Tom",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
db.Create(&user) // 插入一条记录
```
这样,user记录的CreatedAt和UpdatedAt字段值就会被设置为当前时间。如果你需要查询某个时间段内的记录,你可以使用GORM提供的Where条件查询:
```go
startTime := time.Now().AddDate(-10, 0, 0) // 获取当前时间减去10年
endTime := time.Now() // 获取当前时间
var users []User
db.Where("created_at BETWEEN ? AND ?", startTime, endTime).Find(&users)
fmt.Printf("查询到%d条记录:\n", len(users))
for _, user := range users {
fmt.Printf("%d %s %s %s\n", user.ID, user.Name, user.CreatedAt, user.UpdatedAt)
}
```
这个例子中,我们使用了Where条件查询,查询createdAt字段在startTime和endTime之间的所有记录。其中,startTime和endTime分别表示当前时间减去10年和当前时间。在查询结果中,我们打印了每条记录的ID、Name、CreatedAt和UpdatedAt字段值。