预加载示例
GORM允许使用 Preload
通过多个SQL中来直接加载关系, 例如:
Go
type User struct {
gorm.Model
Username string
Orders []Order
}
type Order struct {
gorm.Model
UserID uint
Price float64
}
// 查找 user 时预加载相关 Order
db.Preload("Orders").Find(&users)
// SELECT * FROM users;
// SELECT * FROM orders WHERE user_id IN (1,2,3,4);
db.Preload("Orders").Preload("Profile").Preload("Role").Find(&users)
// SELECT * FROM users;
// SELECT * FROM orders WHERE user_id IN (1,2,3,4); // has many
// SELECT * FROM profiles WHERE user_id IN (1,2,3,4); // has one
// SELECT * FROM roles WHERE id IN (4,5,6); // belongs to
Go
var u []User
db.Debug().Preload("Articles").Find(&u)
fmt.Println(u)
[1.486ms] [rows:7] SELECT * FROM `article` WHERE `article`.`user_id` IN (1,2,3)
[2.644ms] [rows:3] SELECT * FROM `user`
[{1 lucas [{1 golang 1} {2 k8s 1}]} {2 yanzi [{3 golang 2} {4 k8s 2}]} {3 test [{5 redis 3} {6 cherry 3} {7 marry 3}]}]
preload的原理
其实很简单,你要preload user表 的数据,gorm就提前把这张表全部取出来,然后再执行First或Find这样的方法去查询主数据,最后把两种数据一一对应起来。
Go
var u User
db.Debug().Preload("Articles").Take(&u, "name = ?", "test")
fmt.Println(u)
[2.007ms] [rows:3] SELECT * FROM `article` WHERE `article`.`user_id` = 3
[3.056ms] [rows:1] SELECT * FROM `user` WHERE name = 'test' LIMIT 1
{3 test [{5 redis 3} {6 cherry 3} {7 marry 3}]}