gpt4 book ai didi

mysql - GORM 中的多个一对多关系

转载 作者:行者123 更新时间:2023-12-01 19:47:22 25 4
gpt4 key购买 nike

我有一个 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

最佳答案

这就是你要找的:

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)

关于mysql - GORM 中的多个一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60001452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com