gorm:"..." namespace to control column names, types, constraints, and behavior.
Basic model definition
A GORM model is any Go struct. GORM will infer the table name and column names from the struct and field names.users table with columns id, name, email, age, created_at, and updated_at.
The gorm.Model embedded struct
gorm.Model is a convenience struct you can embed in your models to get four standard fields automatically.
users table the columns id, created_at, updated_at, and deleted_at in addition to name and email.
DeletedAt is a gorm.DeletedAt type (backed by sql.NullTime). When a record is deleted, GORM sets this field to the current time rather than removing the row. Queries automatically filter out soft-deleted rows.Struct tags
Use thegorm:"..." struct tag to configure field behavior. Multiple options are separated by semicolons.
Primary keys
By default, GORM treats a field namedID as the primary key. If the field is an integer or unsigned integer type, GORM also enables auto-increment.
primaryKey tag:
string or uuid type:
Column naming
GORM converts CamelCase field names to snake_case column names by default. TheNamingStrategy in schema/naming.go handles common initialisms (such as ID, URL, HTTP) so they don’t produce awkward column names.
| Field name | Column name |
|---|---|
Name | name |
FirstName | first_name |
UserID | user_id |
APIKey | api_key |
HTTPSPort | https_port |
column tag:
Table naming
GORM pluralizes the struct name in snake_case to derive the table name:User → users, OrderItem → order_items.
Override the table name by implementing the Tabler interface:
TableName() must have a value receiver, not a pointer receiver, when used with gorm.DB.AutoMigrate or schema parsing.Field-level tags reference
column
column
Sets the database column name.
type
type
Sets the SQL column type. Accepts database-specific types.
size
size
Sets the column size/length, primarily for strings.
not null
not null
Adds a
NOT NULL constraint to the column.default
default
Sets a default value for the column. Can be a literal value or a database function.
uniqueIndex
uniqueIndex
Creates a unique index on the column.
index
index
Creates a non-unique index on the column.
primaryKey
primaryKey
Marks the field as the primary key.
autoIncrement
autoIncrement
Enables auto-increment for integer primary keys. Set to
false to disable.autoCreateTime
autoCreateTime
Marks the field as the creation timestamp. Accepts
nano or milli to store Unix nanoseconds or milliseconds instead of a time.Time.autoUpdateTime
autoUpdateTime
Marks the field as the update timestamp. Same precision options as
autoCreateTime.-
-
Excludes the field from all database operations.
<- and ->
<- and ->
Control field read/write permissions.