【问题标题】:One-to-many associations not working with test entries一对多关联不适用于测试条目
【发布时间】:2021-01-17 05:22:06
【问题描述】:

和这个问题类似,但是在一对多的情况下: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"}}}

但是,电子邮件条目不会与用户对象相关联。

User 对象没有其所引用的 Email 对象的条目是否正常(与“引用”的情况相反)?

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

所有电子邮件都可以通过

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

【问题讨论】:

    标签: go associations one-to-many go-gorm


    【解决方案1】:

    您需要通过引用其列名预加载(急切加载)电子邮件表:

    user := &User{}
    db.Preload("Emails").First(user)
    

    如果您使用的是一对一关系,您也可以通过调用自动完成:

    db.Preload(clause.Associations).Find(user)
    

    注意:这适用于一对多关系。

    GORM Docs 中定义了一些其他功能,例如嵌套预加载,以及将连接和预加载组合在一起(用于过滤或对子表排序)

    【讨论】:

    • 这个问题只是关于一对母,所以我认为预加载不起作用?
    • @Heikkisorsa 明确执行Preload("Emails") 将预加载一对多。其他示例仅用于一对一。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 2018-02-03
    • 2022-11-14
    相关资源
    最近更新 更多