亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

一對多關聯

一對多關聯

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 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號