GORM
01 / 02

Models, Conventions & the Chainable Query API

Models, Conventions & the Chainable Query API

Go's Most-Used ORM

GORM provides model definitions, associations, migrations, and a chainable query API on top of SQL databases (PostgreSQL, MySQL, SQLite, SQL Server) via pluggable drivers.

Convention-Based Model Mapping

type User struct {
    gorm.Model
    FirstName string
    Email     string `gorm:"uniqueIndex"`
}
// maps to table "users", column "first_name" — both overridable via struct tags

A struct maps to a table by convention (pluralized, snake_case), and fields must be exported (capitalized) — GORM relies on reflection, which can't see unexported fields. gorm.Model embeds ID, CreatedAt, UpdatedAt, and DeletedAt, the last of which enables soft-delete: Delete sets that timestamp instead of removing the row, and default queries filter such rows out automatically.

Chaining Queries

var users []User
db.Where("active = ?", true).
   Order("created_at desc").
   Select("id", "first_name", "email").
   Find(&users)

var user User
db.First(&user, 1) // by primary key

Each chained method returns a new *gorm.DB session with the clause added; SQL only executes when a terminal method (Find, First, Save, ...) is called. First fetches a single record (erroring if none found); Find populates a slice with all matches. Select restricts which columns are fetched, rather than the default full-row scan.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free