gorm.Model
now:
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
new:
type Model struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
}
You don't have to use gorm.Model in your structs. gorm.Model isn't required and doesn't do anything apart from providing these fields. Instead, GORM looks for fields with the names "ID", "CreatedAt", and so on and updates them accordingly (relevant documentation).
This means that you can define your own "base model" struct:
type MyModel struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
}
and use it in your structs:
type User struct {
MyModel
Name string `json:"name"`
}
The fields from MyModel will be treated the same way as those defined in gorm.Model.
Most helpful comment
You don't have to use
gorm.Modelin your structs.gorm.Modelisn't required and doesn't do anything apart from providing these fields. Instead, GORM looks for fields with the names "ID", "CreatedAt", and so on and updates them accordingly (relevant documentation).This means that you can define your own "base model" struct:
and use it in your structs:
The fields from
MyModelwill be treated the same way as those defined ingorm.Model.