这是我的律师模型
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"`
}最后是我的PracticeArea模型
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)这个结果也包含所有律师和LawyerPracticeAreas数据,但不包含来自LawyerPracticeAreas中的PracticeArea表的数据。
律师和PracticeArea有很多-2-多的关系,LawyerPracticeAreas就是那张桌子.

如您所见,我接收的是practiceAreas数组,而不是该PracticeArea的数据。
在一个查询中是否也有任何方法来查询这个问题,或者我是否必须遍历我的所有律师,然后是practiceAreas,然后对每个id查找practiceArea数据。
发布于 2022-04-21 14:56:33
每文档
clause.Associations不会预加载嵌套关联,但是您可以将它与嵌套预加载一起使用.
在您的示例中,要加载所有内容,即使关联嵌套的深度超过一个级别,您也可以这样做:
result := db.Preload("Location").Preload("PracticeAreas.PracticeArea").Find(&lawyer)https://stackoverflow.com/questions/71955327
复制相似问题