gorm.Model
gorm.Model is a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt.
It may be embedded into your model or you may build your own model without it.
// gorm.Model definition |
ID as Primary Key
GORM uses any field with the name ID as the table’s primary key by default.
type User struct { |
Pluralized Table Name
Table name is the pluralized version of struct name.
type User struct {} // default table name is `users` |
Specifying The Table Name
// Create `deleted_users` table with struct User's definition |
Change default tablenames
You can apply any rules on the default table name by defining the DefaultTableNameHandler.
gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string { |
Snake Case Column Name
Column names will be the field’s name is lower snake case.
type User struct { |
Timestamp Tracking
CreatedAt
For models having a CreatedAt field, it will be set to the time when the record is first created.
db.Create(&user) // will set `CreatedAt` to current time |
UpdatedAt
For models having an UpdatedAt field, it will be set to time when the record is updated.
db.Save(&user) // will set `UpdatedAt` to current time |
DeletedAt
For models with a DeletedAt field, when Delete is called on that instance, it won’t truly be deleted from database, but will set its DeletedAt field to the current time. Refer to Soft Delete