In GORM, preloading is a powerful feature for handling associated queries in the database, especially when dealing with multiple models that have relationships. Preloading is primarily designed to address the N+1 query problem, where additional queries are executed for each main entity to load associated data, which can be highly inefficient when working with large datasets.
GORM provides the Preload method to implement preloading, enabling the loading of the main entity and its associated entities in a single query. This feature is particularly useful when handling relationships such as one-to-many or many-to-many.
Example
Assume we have the following two models: User and Order, where one user can have multiple orders:
gotype User struct { gorm.Model Name string Orders []Order } type Order struct { gorm.Model UserID uint Price float64 }
If you want to query a user and all their orders, you can use the Preload method:
go// Initialize database connection (assuming it's already done) db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { log.Fatalf("failed to connect database: %v", err) } // Preload all orders for the user var user User db.Preload("Orders").First(&user, 1) // Assuming we retrieve the user with ID 1 // Now the user object contains all order information fmt.Println("User:", user.Name) for _, order := range user.Orders { fmt.Println("Order ID:", order.ID, "Price:", order.Price) }
In this example, Preload("Orders") ensures that all orders are loaded simultaneously with the user query, avoiding subsequent individual queries for each order.
Advanced Applications
GORM's Preload can handle more complex queries. For instance, if you only want to load the most recent orders or orders with prices exceeding a certain value, you can combine the Where clause with Preload:
godb.Preload("Orders", "price > ?", 100).Find(&users)
This will preload all orders with prices exceeding 100.
In summary, by using GORM's preloading feature, you can effectively optimize database queries and improve application performance, especially when dealing with complex data model relationships.