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 ...