ID as Primary Key

GORM uses the field with the name ID as the table’s primary key by default.

  1. type User struct {
  2.   ID   string // field named `ID` will be used as a primary field by default
  3.   Name string
  4. }

You can set other fields as primary key with tag primaryKey

  1. // Set field `UUID` as primary field
  2. type Animal struct {
  3.   ID     int64
  4.   UUID   string `gorm:"primaryKey"`
  5.   Name   string
  6.   Age    int64
  7. }

Also check out Composite Primary Key

Pluralized Table Name

GORM pluralizes struct name to snake_cases as table name, for struct User, its table name is users by convention

TableName

You can change the default table name by implementing the Tabler interface, for example:

  1. type Tabler interface {
  2. TableName() string
  3. }
  4. // TableName overrides the table name used by User to `profiles`
  5. func (User) TableName() string {
  6.   return "profiles"
  7. }

NOTE TableName doesn’t allow dynamic name, its result will be cached for future, to use dynamic name, you can use Scopes, for example:

  1. func UserTable(user User) func (tx *gorm.DB) *gorm.DB {
  2. return func (tx *gorm.DB) *gorm.DB {
  3. if user.Admin {
  4. return tx.Table("admin_users")
  5. }
  6. return tx.Table("users")
  7. }
  8. }
  9. db.Scopes(UserTable(user)).Create(&user)

Temporarily specify a name

Temporarily specify table name with Table method, for example:

  1. // Create table `deleted_users` with struct User's fields
  2. db.Table("deleted_users").AutoMigrate(&User{})
  3. // Query data from another table
  4. var deletedUsers []User
  5. db.Table("deleted_users").Find(&deletedUsers)
  6. // SELECT * FROM deleted_users;
  7. db.Table("deleted_users").Where("name = ?", "jinzhu").Delete(&User{})
  8. // DELETE FROM deleted_users WHERE name = 'jinzhu';

Check out From SubQuery for how to use SubQuery in FROM clause

NamingStrategy

GORM allows users change the default naming conventions by overriding the default NamingStrategy, which is used to build TableName, ColumnName, JoinTableName, RelationshipFKName, CheckerName, IndexName, Check out GORM Config for details

Column Name

Column db name uses the field’s name’s snake_case by convention.

  1. type User struct {
  2.   ID        uint      // column name is `id`
  3.   Name      string    // column name is `name`
  4.   Birthday  time.Time // column name is `birthday`
  5.   CreatedAt time.Time // column name is `created_at`
  6. }

You can override the column name with tag column or use NamingStrategy

  1. type Animal struct {
  2.   AnimalID int64     `gorm:"column:beast_id"`         // set name to `beast_id`
  3.   Birthday time.Time `gorm:"column:day_of_the_beast"` // set name to `day_of_the_beast`
  4.   Age      int64     `gorm:"column:age_of_the_beast"` // set name to `age_of_the_beast`
  5. }

Timestamp Tracking

CreatedAt

For models having CreatedAt field, the field will be set to the current time when the record is first created if its value is zero

  1. db.Create(&user) // set `CreatedAt` to current time
  2. user2 := User{Name: "jinzhu", CreatedAt: time.Now()}
  3. db.Create(&user2) // user2's `CreatedAt` won't be changed
  4. // To change its value, you could use `Update`
  5. db.Model(&user).Update("CreatedAt", time.Now())

You can disable the timestamp tracking by setting autoCreateTime tag to false, for example:

  1. type User struct {
  2. CreatedAt time.Time `gorm:"autoCreateTime:false"`
  3. }

UpdatedAt

For models having UpdatedAt field, the field will be set to the current time when the record is updated or created if its value is zero

  1. db.Save(&user) // set `UpdatedAt` to current time
  2. db.Model(&user).Update("name", "jinzhu") // will set `UpdatedAt` to current time
  3. db.Model(&user).UpdateColumn("name", "jinzhu") // `UpdatedAt` won't be changed
  4. user2 := User{Name: "jinzhu", UpdatedAt: time.Now()}
  5. db.Create(&user2) // user2's `UpdatedAt` won't be changed when creating
  6. user3 := User{Name: "jinzhu", UpdatedAt: time.Now()}
  7. db.Save(&user3) // user3's `UpdatedAt` will change to current time when updating

You can disable the timestamp tracking by setting autoUpdateTime tag to false, for example:

  1. type User struct {
  2. UpdatedAt time.Time `gorm:"autoUpdateTime:false"`
  3. }

NOTE GORM supports having multiple time tracking fields and track with UNIX (nano/milli) seconds, checkout Models for more details