首页 > 解决方案 > 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. 但是下面的查询PatientReport刚才返回的全部是空的。

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回来。有什么建议么?

标签: mysqlgogo-gorm

解决方案


好的,事实证明我只需要问一下,几分钟后我就会自己解决。

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

推荐阅读