温馨提示:本文翻译自stackoverflow.com,查看原文请点击:mysql - Multiple One to Many Relations in GORM
go mysql one-to-many go-gorm

mysql - GORM中的多对多关系

发布于 2020-03-29 13:15:55

我有一个struct定义,GO这样

package models

//StoryStatus indicates the current state of the story
type StoryStatus string

const (
    //Progress indicates a story is currenty being written
    Progress StoryStatus = "progress"
    //Completed indicates a story was completed
    Completed StoryStatus = "completed"
)

//Story holds detials of story
type Story struct {
    ID         int
    Title      string      `gorm:"type:varchar(100);unique_index"`
    Status     StoryStatus `sql:"type ENUM('progress', 'completed');default:'progress'"`
    Paragraphs []Paragraph `gorm:"ForeignKey:StoryID"`
}

//Paragraph is linked to a story
//A story can have around configurable paragraph
type Paragraph struct {
    ID        int
    StoryID   int
    Sentences []Sentence `gorm:"ForeignKey:ParagraphID"`
}

//Sentence are linked to paragraph
//A paragraph can have around configurable paragraphs
type Sentence struct {
    ID          uint
    Value       string
    Status      bool
    ParagraphID uint
}

GORM在GO中使用orm。如何获取所有信息的story基础上story id像所有的paragraphs,所有的sentences每一个paragraph

GORM示例仅显示使用2个模型preload

查看更多

查看更多

提问者
Dinesh Gowda
被浏览
128
Trần Xuân Huy 2020-01-31 23:35

这是您要寻找的:

db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
defer db.Close()

story := &Story{}
db.Preload("Paragraphs").Preload("Paragraphs.Sentences").First(story, 1)

它找到带有的故事id = 1并预先加载其关系

fmt.Printf("%+v\n", story)

这为您很好地打印了结果

旁注:您可以打开Gorm的日志模式,以便查看基础查询,进行调试或任何其他用途:

db.LogMode(true)