For Example:

GORM prefer convention over configuration, by default, GORM uses as primary key, pluralize struct name to snake_cases as table name, snake_case as column name, and uses CreatedAt, UpdatedAt to track creating/updating time

If you follow the conventions adopted by GORM, you’ll need to write very little configuration/code, If convention doesn’t match your requirements,

GORM defined a gorm.Model struct, which includes fields ID, CreatedAt, UpdatedAt, DeletedAt

  1. // gorm.Model definition
  2. type Model struct {
  3. ID uint `gorm:"primaryKey"`
  4. CreatedAt time.Time
  5. DeletedAt gorm.DeletedAt `gorm:"index"`
  6. }

Exported fields have all permission when doing CRUD with GORM, and GORM allows you to change the field-level permission with tag, so you can make a field to be read-only, write-only, create-only, update-only or ignored

GORM use CreatedAt, UpdatedAt to track creating/updating time by convention, and GORM will set the current time when creating/updating if the fields are defined

To use fields with a different name, you can configure those fields with tag autoCreateTime, autoUpdateTime

  1. type User struct {
  2. CreatedAt time.Time // Set to current time if it is zero on creating
  3. Updated int64 `gorm:"autoUpdateTime:nano"` // Use unix nano seconds as updating time
  4. Updated int64 `gorm:"autoUpdateTime:milli"`// Use unix milli seconds as updating time
  5. Created int64 `gorm:"autoCreateTime"` // Use unix seconds as creating time
  6. }

For anonymous fields, GORM will include its fields into its parent struct, for example:

For a normal struct field, you can embed it with the tag embedded, for example:

  1. type Author struct {
  2. Name string
  3. Email string
  4. type Blog struct {
  5. ID int
  6. Author Author `gorm:"embedded"`
  7. Upvotes int32
  8. }
  9. // equals
  10. type Blog struct {
  11. ID int64
  12. Name string
  13. Email string
  14. Upvotes int32

And you can use tag embeddedPrefix to add prefix to embedded fields’ db name, for example:

Tags are optional to use when declaring models, GORM supports the following tags:
Tags are case insensitive, however camelCase is preferred.