Preload
GORM allows eager loading relations in other SQL with Preload, for example:
Generics API
type User struct { |
Traditional API
// Preload Orders when find users |
Joins Preloading
Preload loads the association data in a separate query, Join Preload will loads association data using left join, for example:
Generics API
type User struct { |
Traditional API
db.Joins("Company").Joins("Manager").Joins("Account").First(&user, 1) |
Join with conditions
db.Joins("Company", DB.Where(&Company{Alive: true})).Find(&users) |
Join nested model
db.Joins("Manager").Joins("Manager.Company").Find(&users) |
NOTE
Join Preloadworks with one-to-one relation, e.g:has one,belongs to
Preload All
clause.Associations can work with Preload similar like Select when creating/updating, you can use it to Preload all associations, for example:
type User struct { |
clause.Associations won’t preload nested associations, but you can use it with Nested Preloading together, e.g:
db.Preload("Orders.OrderItems.Product").Preload(clause.Associations).Find(&users) |
Preload with conditions
GORM allows Preload associations with conditions, it works similar to Inline Conditions
// Preload Orders with conditions |
Custom Preloading SQL
You are able to custom preloading SQL by passing in func(db *gorm.DB) *gorm.DB, for example:
db.Preload("Orders", func(db *gorm.DB) *gorm.DB { |
Nested Preloading
GORM supports nested preloading, for example:
db.Preload("Orders.OrderItems.Product").Preload("CreditCard").Find(&users) |
Embedded Preloading
Embedded Preloading is used for Embedded Struct, especially the
same struct. The syntax for Embedded Preloading is similar to Nested Preloading, they are divided by dot.
For example:
type Address struct { |
We can omit embedded part when there is no ambiguity.
type Address struct { |
NOTE
Embedded Preloadonly works withbelongs torelation.
Values of other relations are the same in database, we can’t distinguish them.