GORM relationships: belongs to, has many, many to many
A relationship in GORM is two things at once: a field on a Go struct, which is how your code reads it, and a foreign key column, which is how the database stores it. Most confusion with GORM comes from reading one and expecting the other.
Each relation below is drawn, then written as a struct, then shown as the SQL GORM produces. If you only read one section, read the one on loading them, because that is where the performance goes.
18 min read. Commands and output last run against Grit v3.560.0.
What you will have at the end
The four relation kinds, with the struct tags that make each one work.
The ability to predict which column GORM will look for, which is what the error messages are really telling you.
Eager loading, and why a list endpoint got slow after you added an author name.
The conventions, before the relations
GORM guesses a great deal from names. Knowing the guesses turns its error messages from mysterious into obvious.
- A struct called
Postmaps to a table calledposts: pluralised, snake_cased. - A field called
AuthorIDbecomes a column calledauthor_id. - A field named
IDis the primary key, and is auto-incrementing if it is an integer. CreatedAtandUpdatedAtare maintained for you if present.DeletedAt gorm.DeletedAtturns on soft delete for the whole model.
One naming trap worth knowing now
GORM splits names on case boundaries, and it does not know your initialisms. A field called AllowIDPInitiated becomes the column allow_id_p_initiated, not allow_idp_initiated. If a column name ever looks mangled, pin it explicitly with gorm:"column:allow_idp_initiated" rather than fighting the conversion.
Belongs to: the many side holds the key
A post belongs to one user. The foreign key lives on posts, which is the side that can have many rows pointing at the same user.
type Post struct {ID uint `gorm:"primaryKey"`Title string// The column. This is what the database actually stores.AuthorID uint `gorm:"index;not null"`// The Go-side field. Empty until you load it; GORM never fills it in// by accident, which is the behaviour people find surprising.Author User}type User struct {ID uint `gorm:"primaryKey"`Name string}
The pairing is by name: GORM sees a field of type User called Author, and looks for AuthorID. Name the field Writer and it looks for WriterID. When they do not line up, say so:
Author User `gorm:"foreignKey:CreatedByID;references:ID"`
Index the foreign key
gorm:"index" on AuthorID is not optional in practice. Every "posts by this author" query filters on it, and without an index that is a full table scan. Postgres creates an index for a primary key and not for a foreign key, which catches people who assume otherwise.
Has many: the same key, read the other way
Has-many is belongs-to seen from the other end. There is no new column: the same author_id on posts supports both directions.
type User struct {ID uint `gorm:"primaryKey"`Name string// A slice, so "many". GORM looks on Post for a UserID, because this// struct is called User. Ours is called AuthorID, so say so.Posts []Post `gorm:"foreignKey:AuthorID"`}
Declaring both sides is optional. Declare the side you will actually read from; a relation nobody traverses is a field that confuses the next reader.
What happens to the children when the parent goes
Deleting a user with posts leaves orphaned rows pointing at an id that no longer exists, unless you say otherwise. Decide this deliberately:
// The database enforces it: deleting a user deletes their posts.Posts []Post `gorm:"foreignKey:AuthorID;constraint:OnDelete:CASCADE"`// Or keep the posts and null the author, for "deleted user" content.AuthorID *uint `gorm:"index"`Posts []Post `gorm:"foreignKey:AuthorID;constraint:OnDelete:SET NULL"`
Note the pointer in the second version. A nullable foreign key must be *uint, because a plain uint cannot hold null and GORM will write 0, which is a row pointing at a user that does not exist.
Has one: a belongs-to that happens to be unique
type User struct {ID uint `gorm:"primaryKey"`Profile Profile}type Profile struct {ID uint `gorm:"primaryKey"`// uniqueIndex is what makes this has-ONE rather than has-many. Without// it the schema permits two profiles per user and only your code// objects, which means it will happen.UserID uint `gorm:"uniqueIndex;not null"`Bio string}
Worth asking whether you need it at all. A profile with three fields is usually three more columns on users. Split the table when the data is genuinely optional, genuinely large, or has a different access pattern: a thousand-character bio you never select in a list is a reasonable split.
Many to many: a third table does the work
A post has many tags and a tag has many posts, so neither table can hold the key. A join table does, with one row per pairing.
type Post struct {ID uint `gorm:"primaryKey"`Tags []Tag `gorm:"many2many:post_tags;"`}type Tag struct {ID uint `gorm:"primaryKey"`Name string `gorm:"uniqueIndex;not null"`Posts []Post `gorm:"many2many:post_tags;"`}
GORM creates post_tags with post_id and tag_id, and manages it. Adding and removing happens through the association API rather than by touching the join table:
db.Model(&post).Association("Tags").Append(&tag) // add onedb.Model(&post).Association("Tags").Delete(&tag) // remove onedb.Model(&post).Association("Tags").Replace(tags) // set the whole list
When the join needs its own fields
The moment the relationship itself has attributes, the implicit join table stops being enough. "User is a member of Organisation" is many-to-many, until somebody asks what their role is, or when they joined.
// A real model, not an implicit table, because the membership has data.type Membership struct {ID uint `gorm:"primaryKey"`UserID uint `gorm:"index;uniqueIndex:idx_user_org;not null"`OrganisationID uint `gorm:"index;uniqueIndex:idx_user_org;not null"`Role string `gorm:"not null;default:'member'"`JoinedAt time.Time}
The shared uniqueIndex:idx_user_org name on both columns makes one composite unique index, which is what stops the same person being added twice. Enforce it in the database rather than in a handler: a second write path will eventually arrive that does not check.
Loading them, and the query that ruins a list endpoint
This is the section that matters for performance. A relationship field is empty until you ask for it, and how you ask decides whether your endpoint runs one query or five hundred.
Preload: a second query, then stitching
var posts []Postdb.Preload("Author").Find(&posts)// SELECT * FROM posts;// SELECT * FROM users WHERE id IN (1,2,3,...); <- one more, not one each
Two queries regardless of how many posts come back. Nested relations use a dotted path, and a preload can be filtered:
db.Preload("Author").Preload("Comments.User").Find(&posts)db.Preload("Comments", func(db *gorm.DB) *gorm.DB {return db.Where("approved = ?", true).Order("created_at DESC").Limit(5)}).Find(&posts)
Joins: one query, for belongs-to and has-one
db.Joins("Author").Find(&posts)// SELECT posts.*, Author.* FROM posts LEFT JOIN users "Author" ON ...
One query instead of two, and it lets you filter on the related table. Use it for the single-record relations. Do not use it for has-many: joining one post to its forty comments returns the post forty times, and the row count multiplies with every additional has-many you join.
The N+1
// One query for the list, and then one more per row, in a loop that// does not look like it is querying anything.db.Find(&posts)for i := range posts {db.First(&posts[i].Author, posts[i].AuthorID) // 500 posts, 501 queries}
It is invisible locally, where the database is on the same machine and the dataset is small. In production, with a millisecond of network latency per query, five hundred rows is half a second of waiting for data you could have fetched in two queries.
Watch for the version that hides inside a serialiser or a view helper, where the loop is in one file and the query is in another. The fix is always the same: load what you need before the loop.
Make it visible
Turn on query logging in development and watch the count while you click around. An N+1 announces itself immediately when you can see the queries and is nearly impossible to notice when you cannot.
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info), // development only})
Getting the tables made
AutoMigrate compares your structs to the database and adds what is missing: tables, columns, indexes and foreign keys.
// Order matters: a table referenced by a foreign key must exist first.db.AutoMigrate(&User{}, &Profile{}, &Post{}, &Tag{})
What it will not do, and this is the whole reason production needs something else:
- It never drops a column. Removing a field from the struct leaves the column there.
- It never renames. Renaming a field adds a new column and leaves the old one, with your data in it.
- It will not narrow a type, because that could lose data.
- You cannot review it before it runs. There is no file to read in a pull request and no way to roll it back.
So: AutoMigrate in development, versioned SQL files in production. The migrations reference covers the pattern.
Declaring relations from the command line
Grit generates these from a field list, which is mostly useful because it writes the matching TypeScript, the Zod schema and the admin picker at the same time, so the three cannot disagree.
$grit generate resource Post \--fields "title:string:required,body:text,author:belongs_to:User,tags:many_to_many:Tag"
A belongs_to field produces the foreign key, the index, the Go field, a searchable relationship picker in the admin showing the related record's label, and the preload on the list endpoint, which is the part people forget and then diagnose as an N+1 three months later.
Frequently asked questions
- Why is my Author field empty when the post loaded fine?
- Because GORM does not load relations unless you ask.
db.First(&post)fetches thepostsrow and nothing else, sopost.Authoris a zero-valued struct andpost.AuthorIDholds the real information. Add.Preload("Author")or.Joins("Author"). This is deliberate: the alternative is an ORM that fetches half your database because you touched a field. - Preload or Joins?
Joinsfor belongs-to and has-one: one query, and you can filter on the related table.Preloadfor has-many and many-to-many: joining those multiplies your rows, and with two has-many relations in one query the row count is the product of both. When unsure,Preloadis the safer default.- Should I use many2many or write the join model myself?
many2manywhile the relationship is only a link. Write the model the moment the link has attributes of its own, a role, a quantity, a joined date, or needs its own timestamps or soft delete. Migrating later is possible and tedious, so if you can imagine the attribute arriving, write the model now.- Does AutoMigrate delete data?
- Not by itself: it only adds. The danger is the other direction. It leaves columns you removed and duplicates columns you renamed, so the schema quietly drifts from the struct, and then one day somebody writes a cleanup migration from the struct and drops a column that still has data in it.
- Why is a nullable foreign key a pointer?
- Because a plain
uintcannot represent null: its zero value is 0, so GORM writes 0, and you get a row pointing at a record with id 0 that does not exist.*uintdistinguishes "no author" from "author zero". The same applies to any optional column: use a pointer, orsql.NullStringand friends.
Next steps
- Build your first full-stack appWhere the first model and the first AutoMigrate call come from.
- Build a REST API with GinThe handlers that read and write these models.
- Models referenceEvery field type a generated model can carry, and the tags each produces.
- MigrationsWhat replaces AutoMigrate when the database has data you care about.
