GORM-成功db.Save()后如何查询关联>> [

问题描述 投票:0回答:1
我正在与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。有什么建议吗?

我正在与Gorm和Graphql合作。直到尝试使用它们的外键关系连接两个现有项目之前,我都没有遇到过查询数据的问题。这是我的两个模型:输入Report ...

mysql go gorm
1个回答
0
投票
好吧,事实证明,我只需要问一下,然后几分钟后我便会自行解决。
© www.soinside.com 2019 - 2024. All rights reserved.