Models, Migrations, and Relationships

There is a moment in every Go developer's life when they stare at a raw SQL string spread across four lines, with a fifth line of rows.Scan(&a, &b, &c, &d, &e, &f), and think: surely there's a better way.

There is. It's called an ORM, and in the Go world the popular one is GORM. It translates between the world of Go structs and the world of database tables, so you can say "save this user" instead of hand-writing an INSERT statement and wrangling columns.

But GORM is also a tool with sharp corners. Used well, it saves hours. Used carelessly, it produces the kind of bug where your page makes 400 database queries to show ten items and nobody understands why the server sounds like it's trying to take off. This article is about using it well.

What an ORM really is: a translator at a meeting

Imagine two people at a business meeting. One speaks only Go. The other speaks only SQL. They need to collaborate, and between them sits an interpreter, GORM.

You say, in Go: db.Create(&user).

GORM turns that into: INSERT INTO users (email, created_at, ...) VALUES (...).

The database replies with rows, and GORM translates them back into your structs. A good interpreter makes the meeting smooth. A bad one, or a good one you don't understand, can make you say things you didn't mean. So you still need to know a little of both languages. We'll sneak a look at the generated SQL later.

Connecting to PostgreSQL

First, the setup:

import ( "gorm.io/driver/postgres" "gorm.io/gorm" ) func Connect(dsn string) (*gorm.DB, error) { db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { return nil, fmt.Errorf("connecting to database: %w", err) } return db, nil } 

The dsn is a connection string such as:

host=localhost user=app password=secret dbname=appdb port=5432 sslmode=disable 

Load it from an environment variable, never hard-code it. Credentials committed to a repository have a way of becoming everybody's credentials.

Models: structs with a double life

A GORM model is a regular Go struct. GORM reads its fields and figures out the table.

type User struct { ID uint `gorm:"primaryKey"` Email string `gorm:"uniqueIndex;not null;size:255"` PasswordHash string `gorm:"not null"` Name string `gorm:"size:100"` CreatedAt time.Time UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` } 

Let's decode the tags, the little strings in backticks:

  • primaryKey: this field uniquely identifies each row.
  • uniqueIndex: the database will refuse two users with the same email, and will find users by email quickly.
  • not null: the column can't be empty.
  • size:255: the column's maximum length.

Two things happen automatically here, and they're worth knowing.

Naming conventions. GORM turns User into a table called users (lowercase, plural) and PasswordHash into a column called password_hash. You don't need to write that mapping yourself. It's convention over configuration, and it works until the day you have a table named something irregular, at which point you can override it.

Timestamps. Fields named CreatedAt and UpdatedAt are filled in for you. Free bookkeeping.

The shortcut: gorm.Model

GORM offers a ready-made struct you can embed:

type Product struct { gorm.Model Name string Price int } 

gorm.Model gives you ID, CreatedAt, UpdatedAt, and DeletedAt without typing them. It's handy for quick projects. Many teams prefer writing their own base struct for clarity, but both are fine.

Soft delete: the "are you sure?" button

See that DeletedAt field? It enables soft deletion. When you call db.Delete(&user), GORM doesn't actually remove the row. It stamps deleted_at with the current time, and all later queries quietly skip rows with a stamp.

This is wonderful for "oops, I deleted my account," and for audit trails. It's less wonderful when you assumed the data was gone for privacy reasons, and it's still sitting there. If you need a true delete, use db.Unscoped().Delete(&user). Decide on purpose which kind you want. Don't discover it in a meeting with a lawyer.

Money is not a float (a short, important rant)

Notice that Price above is an int. That's deliberate. Store money in the smallest unit, such as cents or shillings, as an integer, not as a floating-point number. Floats are famous for tiny rounding errors: add 0.1 and 0.2 and you get 0.30000000000000004. Your accountant will not find this charming. If you studied supply chain management, you already know what a stock count that's off by a fraction feels like. Integers keep the books honest.

Migrations: how your database learns about your structs

Your struct describes a table. But the table has to actually exist in PostgreSQL. Migrations are how it gets created and changed.

AutoMigrate: the quick way

GORM can look at your structs and create or update tables automatically:

db.AutoMigrate(&User{}, &Product{}, &Order{}) 

Run this at startup and the tables appear. For learning, prototypes, and small projects, it's great. It adds missing tables, columns, and indexes.

But it has limits you should understand before you trust it with anything real:

  • It won't delete columns you've removed from the struct. (That's a safety feature.)
  • It won't reliably handle renames. Rename Name to FullName and it thinks you added a new column and abandoned the old one.
  • There's no history. You can't answer "what changed in the schema last Tuesday?"
  • It runs at app startup, so a bad change can break production at the worst possible moment.

Versioned migrations: the grown-up way

For anything serious, use migration files: numbered SQL scripts you run in order. Tools such as golang-migrate or goose do this well.

migrations/ ├── 000001_create_users.up.sql ├── 000001_create_users.down.sql ├── 000002_add_name_to_users.up.sql └── 000002_add_name_to_users.down.sql 

Each up file moves the schema forward. Each down file undoes it. The result is a clear, reviewable history, and every environment, from your laptop to production, ends up with the identical structure.

A sensible path: use AutoMigrate while exploring ideas, then switch to versioned migrations once the schema starts to matter. The point isn't to be fancy. It's that schema changes should be deliberate, recorded, and reversible, like contracts instead of sticky notes.

Relationships: how tables hold hands

Real data is connected. A user has orders. An order has items. Students take many courses, and courses have many students. GORM models these with struct fields.

Belongs to and has many

The most common relationship: one user has many orders, and each order belongs to one user.

type User struct { ID uint Email string Orders []Order // a user HAS MANY orders } type Order struct { ID uint Total int UserID uint // the foreign key User User // an order BELONGS TO a user } 

The UserID field is the foreign key, the number in the orders table that points back at a row in users. GORM spots the naming pattern (User plus ID) and wires it up. Think of it as each order carrying a name tag that says "I belong to user #7."

Many to many

Now a trickier case: students and courses.

type Student struct { ID uint Name string Courses []Course `gorm:"many2many:student_courses;"` } type Course struct { ID uint Title string Students []Student `gorm:"many2many:student_courses;"` } 

GORM creates a third table, student_courses, a junction table that records which student is paired with which course. You never touch it directly. It works like a guest list kept at the door: not part of either family, but it knows who's connected to whom.

The N+1 problem: how to melt your server politely

Now the part where the sharp corner lives. Suppose you want to list users along with their orders:

var users []User db.Find(&users) for _, u := range users { var orders []Order db.Where("user_id = ?", u.ID).Find(&orders) // do something with orders } 

Looks reasonable. But count the queries. One to fetch the users, then one more per user. With 100 users, that's 101 queries. With 10,000 users, you've built a denial-of-service attack against yourself.

This is the N+1 problem, and it's the most famous ORM trap. It's like going to the supermarket and making a separate trip for every single item on your list. Each trip is fast. Together, they take all day.

The fix is Preload:

var users []User db.Preload("Orders").Find(&users) 

Now GORM runs two queries: one for users, one for all their orders together, then stitches them up in memory. Two trips instead of 101.

You can nest and filter too:

db.Preload("Orders", "total > ?", 1000). Preload("Orders.Items"). Find(&users) 

A habit worth building: whenever you loop over results and call the database inside the loop, stop. That's almost always an N+1 waiting to happen.

Peeking at the SQL (learn the other language)

Earlier I said you should know a bit of both languages. Here's the easiest way. Turn on debug mode for a query:

db.Debug().Where("email = ?", "a@b.com").First(&user) 

GORM prints the exact SQL it ran, with timing. Read it. You'll start noticing when GORM does something silly, like selecting every column when you needed one, and you'll learn SQL almost by accident. For general logging, set a logger in the config, and keep the noisy version for development only.

Querying without footguns

A few everyday operations, done safely.

Always use placeholders.

// Safe db.Where("email = ?", email).First(&user) // Dangerous: SQL injection waiting to happen db.Where("email = '" + email + "'").First(&user) 

The question mark lets GORM send the value separately from the query, so a malicious input like '; DROP TABLE users;-- is treated as plain text and not as an instruction. Never glue user input into SQL strings. Ever.

Know the difference between First and Find. First returns an error (gorm.ErrRecordNotFound) if nothing matches. Find into a slice just returns an empty slice with no error. Mixing up their behavior leads to "why is my not-found check never triggering?" afternoons.

Update carefully. db.Save(&user) writes every field. db.Model(&user).Update("name", "Amina") changes just one. If you pass a struct to Updates, GORM ignores zero values like 0, "", and false, so you can't set a field to blank that way. Use a map when you need that:

db.Model(&user).Updates(map[string]interface{}{"name": ""}) 

Transactions: all or nothing

Some operations must succeed together or not at all. Moving money between accounts is the classic example: subtract from A, add to B. If the server dies between the two steps, you've vaporized money. Transactions prevent that.

err := db.Transaction(func(tx *gorm.DB) error { if err := tx.Model(&from).Update("balance", gorm.Expr("balance - ?", amount)).Error; err != nil { return err // rolls everything back } if err := tx.Model(&to).Update("balance", gorm.Expr("balance + ?", amount)).Error; err != nil { return err } return nil // commits }) 

Return an error and everything inside is undone. Return nil and it's all saved together. Use tx, not db, inside the function, or the queries escape the transaction like toddlers leaving the playpen.

Keeping GORM in its place

Back to our three layers. All of this database talk belongs in the repository. Your service should say repo.FindUserWithOrders(id) and not know that Preload exists. If your services start importing gorm.io/gorm, the boundary is leaking, and the day you need to change how data is fetched, you'll find GORM calls scattered in places they never should have been.

One more tidy habit: keep your GORM models and your domain structs honest about their different roles. A model with GORM tags is shaped by the database. Your API responses are shaped by what clients need. They overlap, but they aren't the same thing.

Common mistakes

Trusting AutoMigrate in production. It's a helpful assistant, not a release manager. Use versioned migrations once data matters.

Ignoring the .Error. Every GORM call returns a result you must check: if err := db.Create(&u).Error; err != nil. Skipping this means failures pass silently and you get ghost bugs.

Loading everything. db.Find(&users) on a table with a million rows is a bad time. Paginate with Limit and Offset, or better, cursor-style filtering.

Forgetting indexes. If you search by a column often, index it. A query that takes 2ms on 1,000 rows can take 20 seconds on 10 million without one. We'll dedicate an entire article to PostgreSQL indexes next.

Using floats for money. Covered above, and I'll say it again at your wedding.

Quick recap

  • GORM translates between Go structs and SQL tables. Learn the SQL it generates.
  • Model fields become columns, and tags control constraints like uniqueIndex and not null.
  • DeletedAt gives you soft deletes, so decide deliberately whether you want one.
  • AutoMigrate is fine for prototypes. Versioned migrations are for real projects.
  • Relationships come as belongs to, has many, and many to many.
  • Beware N+1 queries, and use Preload to fix them.
  • Always use placeholders, check errors, and wrap multi-step changes in transactions.
  • Keep GORM inside your repositories.