這是我的律師模型
type Lawyer struct {
ID uint `gorm:"primaryKey" json:"id"`
FirstName string `gorm:"type:varchar(100) not null" json:"first_name"`
LastName string `gorm:"type:varchar(100) not null" json:"last_name"`
FullName string `gorm:"->;type:text GENERATED ALWAYS AS (concat(first_name,' ',last_name)) VIRTUAL;" json:"full_name"`
LocationID uint `gorm:"not null" json:"location_id"`
Location Location `gorm:"foreignKey:location_id" json:"location"`
Email string `gorm:"unique;not null" json:"email"`
Phone string `gorm:"type:varchar(100);not null" json:"phone"`
Password string `gorm:"type:varchar(100);not null" json:"password"`
ImageURL string `gorm:"type:text" json:"image_url"`
Education string `gorm:"not null" json:"education"`
Experience uint `gorm:"not null" json:"experience"`
PracticeAreas []LawyerPracticeArea `gorm:"foreignKey:LawyerID" json:"practice_areas"`
CreatedAt time.Time `gorm:"" json:"created_at"`
UpdatedAt time.Time `gorm:"" json:"updated_at"`
}
這是我的 LawyerPracticeAreas 模型
type LawyerPracticeArea struct {
ID uint `gorm:"primaryKey" json:"lawyer_practice_area_id"`
LawyerID uint `gorm:"not null" json:"lawyer_id"`
PracticeAreaID uint `gorm:"not null" json:"practice_area_id"`
PracticeArea PracticeArea `gorm:"foreignKey:PracticeAreaID" json:"practice_area"`
Charge int `gorm:"" json:"charge"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
最后是我的練習區模型
type PracticeArea struct {
ID uint `gorm:"primaryKey" json:"practice_area_id"`
Name string `gorm:"not null" json:"name"`
AvgFee string `gorm:"not null" json:"avg_fee"`
}
我正在通過以下方式查詢我的律師模型:-
result := db.Preload(clause.Associations).Find(&lawyer)
此結果也包含所有 Lawyers 和 LawyerPracticeAreas 資料,但不包含 LawyerPracticeAreas 內的 PracticeArea 表中的資料。
Lawyer 和 PracticeArea 具有多對多的關系,而 LawyerPracticeAreas 就是那個表。

如您所見,我收到了一系列練習區域,但沒有收到該練習區域的資料。
有沒有辦法在一個查詢中也可以查詢,或者我是否必須遍歷我所有的律師,然后是 practiceAreas,然后為每個 id 找到 practiceArea 資料。
uj5u.com熱心網友回復:
根據檔案:
clause.Associations不會預加載嵌套關聯,但您可以將它與嵌套預加載一起使用...
在您的情況下,要加載所有內容,即使是嵌套不止一層的關聯,您也可以這樣做:
result := db.Preload("Location").Preload("PracticeAreas.PracticeArea").Find(&lawyer)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/460614.html
