mysql - 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
并查看patient_id
. 我还可以查询Patient
并查看report_id
. 但是下面的查询Patient
从Report
刚才返回的全部是空的。
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
回来。有什么建议么?
解决方案
好的,事实证明我只需要问一下,几分钟后我就会自己解决。
我Preload()
在 Gorm 文档中读到过,但不知道在哪里实现它。我第一次尝试是在数据库启动时认为它会加载关联。但我真的需要在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
...
}
}
}
推荐阅读
- spring-lemon - 在 SpringLemon 中使用子模块
- haskell - 如何在 Haskell 中从 Set 中提取具有零个或一个元素的元素?
- sql - 使用 SQL 语句的条件排名
- python - 在 python 中使用请求模块连接到 Azure-Datalakes-gen2 时遇到问题
- sql - 为什么我需要在这个子选择中硬编码子句?
- python - 如何将大型 python 模型应用于 pyspark-dataframe?
- c# - 具有多个接口的 Autofac Open Generic Decorator 导致循环依赖解析
- android - 不能在没有 PlayStore 的情况下使用 PackageInstaller
- neural-network - 同时训练DDQN
- c - 关于 C 中的内存