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

通过 Gorm 查询模型

通过 Gorm 查询模型

Go
蝴蝶刀刀 2022-12-05 16:39:48
这是我的律师模型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"`    }最后这是我的 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)此结果也包含所有 Lawyers 和 LawyerPracticeAreas 数据,但不包含来自 LawyerPracticeAreas 内的 PracticeArea 表的数据。Lawyer 和 PracticeArea 具有多对多关系,而 LawyerPracticeAreas 就是该表。
查看完整描述

1 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

根据文档

clause.Associations不会预加载嵌套关联,但您可以将它与嵌套预加载一起使用...

在您的情况下,要加载所有内容,甚至是嵌套超过一层的关联,您可以这样做:

result := db.Preload("Location").Preload("PracticeAreas.PracticeArea").Find(&lawyer)


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

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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