一对多关联

我在GORM中遇到一对多关联的问题。我有这两个结构,我想得到一个病人的完整病史。这是我的示例代码:


type Patient struct {

    gorm.Model

    Prenom     string       `json:"prenom" gorm:"column:patient_prenom"`

    Nom        string       `json:"nom" gorm:"column:patient_nom"`

    Genre      string       `json:"genre" gorm:"column:patient_genre"`

    Naissance  string       `json:"naissance" gorm:"column:patient_naissance"`

    Historique []Historique `gorm:"ForeignKey:Fk_patient_id"`

}

type Historique struct {

    Fk_patient_id        string

    Date_consultation    string

    Fk_maladie_id        uint

    Fk_compte_medecin_id uint

    Patient              Patient

}


func GetPatientWithDiseases(id uint) (*Patient, error) {

    patient := &Patient{}

    //The line right there works so i can retrieve without the history

    //err := GetDB().Find(patient, id).Error

    db := GetDB().Preload("tt_historique").Find(patient)

    err := db.Error


    if err != nil {

        return nil, err

    }

    return patient, nil

}

其中“Historique”使用患者的外键(Fk_patient_id),而Historique []Historique是查询后应最终出现在Patient结构中的每个Historique的列表。


但是我得到这个错误。我已经尝试了多种语法,这些语法是我在结构中的gorm规范中发现的,但没有任何效果。我只使用GO开发了3天,GORM是我的第一个ORM,所以也许我错过了一些非常明显的东西。can't preload field tt_historique for models.Patient


陪伴而非守候
浏览 123回答 1
1回答

HUH函数

根据表名的假设,您需要在此处处理几件事。tt_historique按照惯例,go-gorm 在构造 SQL 查询时使用复数 snake case 结构名称作为数据库表。在您的情况下,要预加载字段,它将查找表。Historique []Historiquehistoriques要覆盖它,您需要实现接口:Tablertype Patient struct {    gorm.Model    Prenom     string       `json:"prenom" gorm:"column:patient_prenom"`    Nom        string       `json:"nom" gorm:"column:patient_nom"`    Genre      string       `json:"genre" gorm:"column:patient_genre"`    Naissance  string       `json:"naissance" gorm:"column:patient_naissance"`    Historique []Historique `gorm:"foreignKey:Fk_patient_id"`}type Historique struct {    Fk_patient_id        string    Date_consultation    string    Fk_maladie_id        uint    Fk_compte_medecin_id uint    Patient              Patient}func (Historique) TableName() string {  return "tt_historique"}然后,您的查询将如下所示:db := GetDB().Preload("Historique").Find(patient)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go