为了账号安全,请及时绑定邮箱和手机立即绑定

一对多关联

一对多关联

Go
陪伴而非守候 2022-08-09 20:41:15
我在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
查看完整描述

1 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

根据表名的假设,您需要在此处处理几件事。tt_historique


按照惯例,go-gorm 在构造 SQL 查询时使用复数 snake case 结构名称作为数据库表。在您的情况下,要预加载字段,它将查找表。Historique []Historiquehistoriques


要覆盖它,您需要实现接口:Tabler


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 (Historique) TableName() string {

  return "tt_historique"

}

然后,您的查询将如下所示:


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


查看完整回答
反对 回复 2022-08-09
  • 1 回答
  • 0 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号