我有一个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)
这就像一个魅力。荣誉!