预加载示例
GORM允许使用 Preload
通过多个SQL中来直接加载关系, 例如:
type User struct { |
Joins 预加载
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
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 { |
嵌套预加载
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.