Din*_*wda 5 mysql one-to-many go go-gorm
我有一个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
}
Run Code Online (Sandbox Code Playgroud)
我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)
Run Code Online (Sandbox Code Playgroud)
它找到带有 的故事id = 1并预加载其关系
fmt.Printf("%+v\n", story)
Run Code Online (Sandbox Code Playgroud)
这会很好地为您打印结果
旁注:您可以打开 Gorm 的日志模式,以便您可以查看底层查询、进行调试或任何其他目的:
db.LogMode(true)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1538 次 |
| 最近记录: |