GORM中的多对多关系 [英] Multiple One to Many Relations in GORM

查看:126
本文介绍了GORM中的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 GO 中有这样的 struct 定义

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
}

我在GO中将 GORM 用于orm.如何根据 story id 获取所有 story 的信息,如所有 paragraphs 和所有 sentences 每个段落.

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.

GORM 示例仅显示两个使用 preload

The GORM example show only with 2 models to use 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 的故事并预载其关系

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

旁注:您可以打开Gorm的日志模式,以便查看基础查询,进行调试或任何其他用途:

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)

这篇关于GORM中的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆