GORM Composite Primary Key — Complete Guide
In this tutorial, you'll learn about GORM Composite Primary Key. We cover key concepts, practical examples, and best practices.
Composite keys in GORM -- Configure composite primary keys by adding gorm:'primaryKey' tags to multiple fields.
The Problem
GORM uses a single ID field as primary key by default. For composite keys, tag multiple fields with gorm:'primaryKey'.
Wrong
type UserRole struct {
UserID uint
RoleID uint
}
db.AutoMigrate(&UserRole{})
Output:
// GORM adds ID column automatically! Not intended.
Right
type UserRole struct {
UserID uint `gorm:'primaryKey'`
RoleID uint `gorm:'primaryKey'`
CreatedAt time.Time
}
db.Where(&UserRole{UserID: 1, RoleID: 2}).First(&ur)
Output:
// Proper composite primary key, no auto-ID
Prevention
- Tag multiple fields with gorm:'primaryKey' for composite keys
- Composite keys ordered by struct field order
- Use gorm:"primaryKey;autoIncrement:false"
- GORM uses all PK fields in WHERE
- Works with associations
Common Mistakes with gorm composite key
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
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