Skip to content

Go Gorm Scopes

DodaTech 1 min read

In this tutorial, you'll learn about GORM Scopes: Query Reuse. We cover key concepts, practical examples, and best practices.

GORM query scopes -- Create reusable query filters to avoid duplicating common WHERE conditions across your codebase.

The Problem

Without scopes, common filters like "active records" are repeated everywhere. GORM scopes are functions returning func(*gorm.DB) *gorm.DB.

Wrong

db.Where("deleted_at IS NULL").Where("status = ?", "active").Find(&users)
db.Where("deleted_at IS NULL").Where("status = ?", "active").First(&user, id)

Output:

// Same condition duplicated everywhere
func Active(db *gorm.DB) *gorm.DB {
    return db.Where("status = ?", "active")
}
db.Scopes(Active, WithoutDeleted).Find(&users)
db.Scopes(Active, WithoutDeleted).First(&user, id)

Output:

// Consistent, reusable filters

Prevention

  • Define scopes as func(*gorm.DB) *gorm.DB
  • Chain multiple scopes: db.Scopes(Scope1, Scope2)
  • Use closures for parameterized scopes
  • Combine with Preload, Joins
  • Work on any query: Find, First, Count, Delete

Common Mistakes with gorm scopes

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

**Can scopes be used with Count?**

Yes. db.Scopes(Active).Count(&count).

Do scopes affect updates?

Yes. db.Scopes(Active).Model(&User{}).Update("name", "new").

Can I use scopes in associations?

Yes. db.Preload("Orders", Active).


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