You can set other fields as primary key with tag primaryKey
// Set field `UUID` as primary field
type Animal struct {
ID int64
UUID string `gorm:"primaryKey"`
Name string
Age int64
}
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:
type Tabler interface {
}
// TableName overrides the table name used by User to `profiles`
func (User) TableName() string {
return "profiles"
}
Temporarily specify table name with Table
method, for example:
// Create table `deleted_users` with struct User's fields
db.Table("deleted_users").AutoMigrate(&User{})
// Query data from another table
var deletedUsers []User
db.Table("deleted_users").Find(&deletedUsers)
// SELECT * FROM deleted_users;
db.Table("deleted_users").Where("name = ?", "jinzhu").Delete(&User{})
// 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.
ID uint // column name is `id`
Birthday time.Time // column name is `birthday`
CreatedAt time.Time // column name is `created_at`
}
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
db.Create(&user) // set `CreatedAt` to current time
user2 := User{Name: "jinzhu", CreatedAt: time.Now()}
db.Create(&user2) // user2's `CreatedAt` won't be changed
// To change its value, you could use `Update`
db.Model(&user).Update("CreatedAt", time.Now())
You can disable the timestamp tracking by setting autoCreateTime
tag to false
, for example:
type User struct {
CreatedAt time.Time `gorm:"autoCreateTime:false"`
}
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:
type User struct {