Go 不使用测试条目的一对多关联

Go 不使用测试条目的一对多关联,go,associations,one-to-many,go-gorm,Go,Associations,One To Many,Go Gorm,与此问题类似,但在一对多的情况下: 我在GORM中定义了两种用户和电子邮件模型:File User.go type User struct { gorm.Model Identity string `json:"identity"` Password string `json:"password"` Emails []Email } type Email struct {

与此问题类似,但在一对多的情况下:

我在GORM中定义了两种用户和电子邮件模型:File 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"`
}
根据以下说明,这应与测试条目一起使用:

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"}}}
但是,电子邮件条目不会与用户对象关联

用户对象没有它所引用的电子邮件对象的条目是正常的吗(与“refere-to”情况相反)

如何查询具有所有相应电子邮件对象的用户

所有电子邮件均可通过

var emails[] Email
db.Where("user_id = ?", id).Find(&emails)

您需要通过引用电子邮件表的列名来预加载电子邮件表:

user:=&user{}
数据库预加载(“电子邮件”)。第一(用户)
如果您使用的是一对一关系,也可以通过调用以下命令自动执行此操作:

db.Preload(子句.Associations).Find(用户)
注意:这将不适用于一对多关系


还有一些其他支持的功能,例如嵌套预加载,以及将联接和预加载组合在一起(用于对子表进行筛选或排序)在

中定义。这个问题只涉及一到一个问题,所以我认为预加载不起作用?@heikkisora显式地执行
预加载(“电子邮件”)
将预加载一对多。其他的例子只是一对一的。