GORM From Zero
Learn Go's most popular ORM: connecting and the model, auto-migration, create and read, querying, update and delete with soft deletes, associations, preloading and the N+1 trap, transactions and hooks and real migrations. The data layer most Go web services use, made plain — including where to drop back to SQL.
- What GORM Is & Connecting GORM is Go's de-facto ORM: structs become tables and *gorm.DB is the query you chain. Open a SQLite connection, turn on the SQL logger, and meet the blog schema.
- Models & Auto-Migration Define tables as Go structs, shape columns with struct tags, embed gorm.Model for ID and timestamps, and let AutoMigrate make the database match your code.
- Create & Read Insert rows with Create and read them back with the four finders — First, Take, Last, and Find — plus the ErrRecordNotFound pattern and why parameterized placeholders keep you safe.
- Querying Build real queries with GORM: Where in all its forms, the struct-vs-map zero-value trap, Order/Limit/Offset for pagination, Select and Count, and reusable scopes — always watching the SQL.
- Update & Delete Updating rows with Update/Updates/Save, the struct zero-value trap (and the map fix), bulk updates with the global-update block, and soft vs hard deletes with Unscoped.
- Associations Wire tables together with GORM: belongs-to, has-many, has-one, and many-to-many. See the foreign keys AutoMigrate builds, create nested records, and manage relations with association mode.
- Preloading & the N+1 Trap GORM never lazy-loads associations, so Posts comes back empty until you ask. Learn Preload's two-query pattern, the N+1 explosion that bites everyone, nested loads, and Joins vs Preload.
- Transactions, Hooks & Migrations Make several writes all-or-nothing with transactions, run your code around DB ops with lifecycle hooks, and version your schema with real migrations instead of leaning on AutoMigrate.
- GORM in the Real World & Where to Go Next Where GORM lands in real Go services: dropping to raw SQL when it helps, GORM vs sqlc/sqlx/ent, the caveats that bite everyone, production pool and context tips, and what to build next.