一对多关联不适用于测试条目
One-to-many associations not working with test entries
类似这个问题,但是在一对多的情况下:
我在 GORM 中定义了两个模型用户和电子邮件:文件 user.go
type User struct {
gorm.Model
Identity string `json:"identity"`
Password string `json:"password"`
Emails []Email
}
type Email struct {
gorm.Model
UserID uint
Text string `json:"text"`
Sender string `json:"sender"`
}
根据 documentation 这应该与测试条目一起工作:
userRec := &user.User{ Identity: "John Wayne", Password: "mysecretpassword", Emails: []user.Email{user.Email{Text: "My Text", Sender: "julia@world.me"}, user.Email{Text: "My Text", Sender: "julia@world.me"}}}
但是,电子邮件条目不会与用户对象相关联。
用户对象没有它所引用的电子邮件对象的条目(与“引用”情况相反)是否正常?
如何查询具有所有相应电子邮件对象的用户?
所有电子邮件都可以通过
var emails[] Email
db.Where("user_id = ?", id).Find(&emails)
您需要预加载(预先加载)电子邮件table,方法是参考其列名:
user := &User{}
db.Preload("Emails").First(user)
如果您正在使用 one-to-one 关系,您也可以通过调用自动完成:
db.Preload(clause.Associations).Find(user)
注意:这 不适用于 one-to-many 关系。
GORM Docs[=13= 中定义了一些其他支持的功能,例如嵌套预加载,以及将联接和预加载组合在一起(用于 sub-tables 上的过滤或排序) ]
类似这个问题,但是在一对多的情况下:
我在 GORM 中定义了两个模型用户和电子邮件:文件 user.go
type User struct {
gorm.Model
Identity string `json:"identity"`
Password string `json:"password"`
Emails []Email
}
type Email struct {
gorm.Model
UserID uint
Text string `json:"text"`
Sender string `json:"sender"`
}
根据 documentation 这应该与测试条目一起工作:
userRec := &user.User{ Identity: "John Wayne", Password: "mysecretpassword", Emails: []user.Email{user.Email{Text: "My Text", Sender: "julia@world.me"}, user.Email{Text: "My Text", Sender: "julia@world.me"}}}
但是,电子邮件条目不会与用户对象相关联。
用户对象没有它所引用的电子邮件对象的条目(与“引用”情况相反)是否正常?
如何查询具有所有相应电子邮件对象的用户?
所有电子邮件都可以通过
var emails[] Email
db.Where("user_id = ?", id).Find(&emails)
您需要预加载(预先加载)电子邮件table,方法是参考其列名:
user := &User{}
db.Preload("Emails").First(user)
如果您正在使用 one-to-one 关系,您也可以通过调用自动完成:
db.Preload(clause.Associations).Find(user)
注意:这 不适用于 one-to-many 关系。
GORM Docs[=13= 中定义了一些其他支持的功能,例如嵌套预加载,以及将联接和预加载组合在一起(用于 sub-tables 上的过滤或排序) ]