获取一对多
最后更新于:2022-04-02 02:37:23
[TOC]
## code
```
type User struct {
gorm.Model
Username string
Orders []Order
}
type Order struct {
gorm.Model
UserID uint
Price float64
}
// 查找 user 时预加载相关 users 的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
```
子结构体若为非引用类型,则在为空时候插入为报子表插入失败,可修改为
```
type User struct {
gorm.Model
Username string
Orders []*Order
}
db.Create(users)
```
';