ID as Primary Key
GORM uses the field with the name ID as the table’s primary key by default.
type User struct { |
You can set other fields as primary key with tag primaryKey
// Set field `UUID` as primary field |
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:
type Tabler interface { |
NOTE
TableNamedoesn’t allow dynamic name, its result will be cached for future, to use dynamic name, you can useScopes, for example:
func UserTable(user User) func (tx *gorm.DB) *gorm.DB { |
Temporarily specify a name
Temporarily specify table name with Table method, for example:
// Create table `deleted_users` with struct User's fields |
Check out From SubQuery for how to use SubQuery in FROM clause
NamingStrategy
GORM allows users to 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.
type User struct { |
You can override the column name with tag column or use NamingStrategy
type Animal struct { |
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
db.Create(&user) // set `CreatedAt` to current time |
You can disable the timestamp tracking by setting autoCreateTime tag to false, for example:
type User struct { |
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
db.Save(&user) // set `UpdatedAt` to current time |
You can disable the timestamp tracking by setting autoUpdateTime tag to false, for example:
type User struct { |
NOTE GORM supports having multiple time tracking fields and track with UNIX (nano/milli) seconds, checkout Models for more details