Предварительная загрузка
GORM позволяет загружать отношения с помощью Preload
, например:
type User struct { |
Join с предварительной загрузкой
Preload
loads the association data in a separate query, Join Preload
will loads association data using left join, for example:
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 Preload
works with one-to-one relation, e.g:has one
,belongs to
Предзагрузить все
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) |
Предзагрузка с условиями
GORM allows Preload associations with conditions, it works similar to Inline Conditions
// Preload Orders with conditions |
Пользовательский 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 Preload
only works withbelongs to
relation. Values of other relations are the same in database, we can’t distinguish them.