【发布时间】: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