For Example:
GORM prefer convention over configuration, by default, GORM uses as primary key, pluralize struct name to snake_cases
as table name, snake_case
as column name, and uses CreatedAt
, UpdatedAt
to track creating/updating time
If you follow the conventions adopted by GORM, you’ll need to write very little configuration/code, If convention doesn’t match your requirements,
GORM defined a gorm.Model
struct, which includes fields ID
, CreatedAt
, UpdatedAt
, DeletedAt
// gorm.Model definition
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
Exported fields have all permission when doing CRUD with GORM, and GORM allows you to change the field-level permission with tag, so you can make a field to be read-only, write-only, create-only, update-only or ignored
GORM use CreatedAt
, UpdatedAt
to track creating/updating time by convention, and GORM will set the current time when creating/updating if the fields are defined
To use fields with a different name, you can configure those fields with tag autoCreateTime
, autoUpdateTime
type User struct {
CreatedAt time.Time // Set to current time if it is zero on creating
Updated int64 `gorm:"autoUpdateTime:nano"` // Use unix nano seconds as updating time
Updated int64 `gorm:"autoUpdateTime:milli"`// Use unix milli seconds as updating time
Created int64 `gorm:"autoCreateTime"` // Use unix seconds as creating time
}
For anonymous fields, GORM will include its fields into its parent struct, for example:
For a normal struct field, you can embed it with the tag embedded
, for example:
type Author struct {
Name string
Email string
type Blog struct {
ID int
Author Author `gorm:"embedded"`
Upvotes int32
}
// equals
type Blog struct {
ID int64
Name string
Email string
Upvotes int32
And you can use tag embeddedPrefix
to add prefix to embedded fields’ db name, for example:
Tags are optional to use when declaring models, GORM supports the following tags:
Tags are case insensitive, however camelCase
is preferred.