db.Save()成功后如何查询关联
时间:2024-04-15
浏览:473
作者:佚名
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《db.Save()成功后如何查询关联》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
问题内容
我正在使用 gorm 和 graphql。直到我尝试使用 foreignkey 关系连接两个现有项目时,我才遇到查询数据的问题。这是我的两个模型:
type report struct {
db.base
ownerid string
patient patients.patient `gorm:"association_name:patient;"`
patientid string
}
type patient struct {
db.base
reportid string
}
我有一个将关系保存到数据库的函数:
func (s *store) addpatienttoreport(ctx context.context, id string, patient *patients.patient) (*report, error) {
// check against user using context
report, err := s.report(ctx, id)
if err != nil {
log.error("could not find report.")
return nil, err
}
report.patientid = patient.id
if err := s.db.save(&report).association("patient").append(patient).error; err != nil {
log.witherror(err).error("add patient failed")
return nil, err
}
return report, nil
}
在上述函数之后,我可以查询 report 并查看 patent_id。我还可以查询 patient 并查看 report_id。但以下从 report 获取整个 patient 的查询仅返回空。
query {
report(id: "report_id") {
id
patientid // this will return the correct patient_id
patient {
id // this field always comes back as an empty string
}
}
}
以下是数据库的设置方式:
// NewConn creates a new database connection
func NewConn(cc ConnConf) (*Conn, error) {
db, err := gorm.Open("mysql", cc.getCtxStr())
if err != nil {
return nil, err
}
// Models are loaded from each package. Patients is created before Reports.
if err := db.AutoMigrate(Models...).Error; err != nil {
log.Fatal(err)
}
db.LogMode(cc.Logger)
return &Conn{db}, err
}
我不知道如何恢复整个 patient。有什么建议吗?
解决方案
好吧,事实证明我只需要问一下,几分钟后我就会自己解决。
我在 gorm 文档中读到了有关 preload() 的内容,但不知道在哪里实现它。当数据库启动时我第一次尝试,认为它会加载关联。但我确实需要在运行查询时使用 preload()。
result := &report{}
if err = s.db.preload("patient").where(&query).first(&result).error; err != nil {
log.withfield("id", id).witherror(err).
error("could not find report")
return nil, err
}
现在,graphql 查询:
query {
report(id: "some_id") {
id
patient {
id // now it returns the id
birthyear // now it returns other fields, too
...
}
}
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
