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

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

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

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

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

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 for details

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

  1.   ID        uint      // column name is `id`
  2.   Birthday  time.Time // column name is `birthday`
  3.   CreatedAt time.Time // column name is `created_at`
  4. }

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. }

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

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

  1. type User struct {