Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple One to Many Relations in GORM

Tags:

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

like image 766
Dinesh Gowda Avatar asked Jan 31 '20 09:01

Dinesh Gowda


1 Answers

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)
like image 86
Trần Xuân Huy Avatar answered Oct 06 '22 00:10

Trần Xuân Huy