Golang学习:gorm的模型声明 | 青训营笔记

110 阅读2分钟

这是我参与「第五届青训营」伴学笔记创作活动的第 8 天,今天对grom进行了简单的学习,学习了gorm中的模型声明,在这里进行一下总结

概念

GORM是一个设计简洁、功能强大、自动扩展的全功能ORM

优点:API精简、测试优先、灵活扩展

模型定义

模型定义: 定义的模型与表是一一对应,我们在查找表时是用这个模型来代替表的,然后来操作数据库中的对应的数据表;模型一般都是结构体、Go的基本数据类型,或者指针、sql.Scanner、driver.Valuer、接口

gorm.Model模型定义: gorm.Model模型是系统自带的一个模型, 包含的字段有 ID, CreatedAt, UpdatedAt, DeletedAt。

// Model a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt
// It may be embedded into your model or you may build your own model without it
//    type User struct {
//      gorm.Model
//    }
type Model struct {
    ID        uint `gorm:"primarykey"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt DeletedAt `gorm:"index"`
}

gorm.Model模型的使用

gorm.Model模型的使用: 可以将Model模型嵌套进自定义的模型结构体中使用

type user struct {
    ID        uint `gorm:"primarykey"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt DeletedAt `gorm:"index"`
    Name     string
    Path     string
}

这样使用就相当于:

type user struct {
    gorm.Model
    Name     string
    Path     string
}

gorm模型定义的约定惯例:

表名为struct name的snake cases复数格式

字段名为 field name的snake_case单数格式

ID/id字段为主键,如果为数字,则为自增主键

CreatedAt字段,创建时,保存当前时间

UpdatedAt字段,创建、更新时,保存当前时间

gorm.DeletedAt字段,默认开启soft delete模式

对时间的追踪:

在GORM中,使用CreatedAt字段和UpdatedAt字段对数据创建的时间和更新的时间进行追踪,当在模型中定义了这些字段,Gorm在创建和更新时间时就会自动使用当前时间

如果需要使用不同类型的时间,可以配置不同的标签,例如

type User struct {
    CreatedAt time.Time // 在创建时,如果该字段值为零值,则使用当前时间填充
    UpdatedAt int       // 在创建时该字段值为零值或者在更新时,使用当前时间戳秒数填充
    Updated   int64 `gorm:"autoUpdateTime:nano"` // 使用时间戳纳秒数填充更新时间
    Updated   int64 `gorm:"autoUpdateTime:milli"` // 使用时间戳毫秒数填充更新时间
    Created   int64 `gorm:"autoCreateTime"`      // 使用时间戳秒数填充创建时间
}