通过 Gorm 查询模型

这是我的律师模型


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 就是该表。

http://img3.mukewang.com/638dae670001264405070315.jpg

蝴蝶刀刀
浏览 141回答 1
1回答

郎朗坤

根据文档:clause.Associations不会预加载嵌套关联,但您可以将它与嵌套预加载一起使用...在您的情况下,要加载所有内容,甚至是嵌套超过一层的关联,您可以这样做:result := db.Preload("Location").Preload("PracticeAreas.PracticeArea").Find(&lawyer)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go