Warm tip: This article is reproduced from stackoverflow.com, please click
go mysql one-to-many go-gorm

Multiple One to Many Relations in GORM

发布于 2020-03-29 12:48:22

I have a struct definition in GO like this

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
}

I am using GORM for orm in GO. How do I fetch all the information for a story based on story id like all the paragraphs and all the sentences for each paragraph.

The GORM example show only with 2 models to use preload

Questioner
Dinesh Gowda
Viewed
66
Trần Xuân Huy 2020-01-31 23:35

This is what you're looking for:

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)

It finds the story with the id = 1 and preloads its relationships

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

This prints out the result nicely for you

Side note: You can turn on log mode of Gorm so that you can see the underlying queries, to debug, or any other purposes:

db.LogMode(true)