1. 预加载

1.1. 预加载

  1. db.Preload("Orders").Find(&users)
  2. //// SELECT * FROM users;
  3. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4);
  4. db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  5. //// SELECT * FROM users;
  6. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4) AND state NOT IN ('cancelled');
  7. db.Where("state = ?", "active").Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  8. //// SELECT * FROM users WHERE state = 'active';
  9. //// SELECT * FROM orders WHERE user_id IN (1,2) AND state NOT IN ('cancelled');
  10. db.Preload("Orders").Preload("Profile").Preload("Role").Find(&users)
  11. //// SELECT * FROM users;
  12. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4); // has many
  13. //// SELECT * FROM profiles WHERE user_id IN (1,2,3,4); // has one
  14. //// SELECT * FROM roles WHERE id IN (4,5,6); // belongs to

1.2. 自动预加载

始终自动预加载的关联

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. CompanyID uint
  5. Company Company `gorm:"PRELOAD:false"` //没有预加载
  6. Role Role // 已经预加载
  7. }
  8. db.Set("gorm:auto_preload", true).Find(&users)

1.3. 嵌套预加载

  1. db.Preload("Orders.OrderItems").Find(&users)
  2. db.Preload("Orders", "state = ?", "paid").Preload("Orders.OrderItems").Find(&users)

1.4. 自定义预加载 SQL

您可以通过传入func(db * gorm.DB)* gorm.DB来自定义预加载SQL,例如:

  1. db.Preload("Orders", func(db *gorm.DB) *gorm.DB {
  2. return db.Order("orders.amount DESC")
  3. }).Find(&users)
  4. //// SELECT * FROM users;
  5. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4) order by orders.amount DESC;