GORM CRUD: Create Returns Empty ID
In this tutorial, you'll learn about GORM CRUD: Create Returns Empty ID. We cover key concepts, practical examples, and best practices.
GORM CRUD operations -- Perform Create, Read, Update, Delete correctly with GORM ensuring the primary key is populated after creation.
The Problem
After db.Create(&user), user.ID should be populated. If ID remains 0, the primary key field is not detected. GORM expects ID or gorm:'primaryKey' tag.
Wrong
type User struct { UserID uint; Name string }
user := User{Name: "Alice"}
db.Create(&user)
fmt.Println(user.UserID) // 0!
Output:
$ go run main.go
0
Right
type User struct {
ID uint `gorm:'primaryKey'`
Name string `gorm:"not null"`
Email string `gorm:"uniqueIndex"`
}
user := User{Name: "Alice"}
result := db.Create(&user)
fmt.Println("Created ID:", user.ID)
Output:
$ go run main.go
Created ID: 1
Prevention
- Always check db.Error after Create
- Use field name ID or tag gorm:'primaryKey'
- Pass pointer to struct (not value) to Create
- Use First or Take for Read
- Use Updates or Save for Update
Common Mistakes with gorm crud
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro