如何使用GORM在GO中预加载完整的层次结构

Gui*_*rré 6 go go-gorm

我有一个由几个结构组成的层次结构

type Entry struct {
    Id          int
    CreatedAt   time.Time
    UpdatedAt   time.Time
    Fields      []Field
}

type SyncField struct {
    Id                   int
    CreatedAt            time.Time
    UpdatedAt            time.Time
    TechnicalName        string
    JsonName             string
    EntryId              int
    Decorators           []Decorator
}

type Decorator struct {
    Id           int
    CreatedAt    time.Time
    UpdatedAt    time.Time
    Name         string
    Description  string
    SortingOrder int
    Params       string
    SyncFieldId  int
}
Run Code Online (Sandbox Code Playgroud)

我的数据库创建定义如下:

db.CreateTable(&Entry{})
db.CreateTable(&SyncField{})
db.Model(&Entry{}).Related(&SyncField{}, "EntryId")

db.CreateTable(&Decorator{})
db.Model(&SyncField{}).Related(&Decorator{}, "DecoratorId")
Run Code Online (Sandbox Code Playgroud)

一切都很清楚,并且可以正常预加载这样的层次结构中的一个"子级别":

entry := &Entry{Id: i}
iDB.Preload("SyncFields").First(entry)
Run Code Online (Sandbox Code Playgroud)

要么

field := &SyncField{Id: idf}
iDB.Preload("Decorators").First(field)
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法,使用GORM预加载整个层次,在其中一个根元素上调用"First()"方法...我想加载一个"条目"及其所有相关的"字段",我也想要让每个"Field"预装所有"装饰者"......

使用几个"Preload()"函数是不可行的:

entry := &Entry{Id: i}
iDB.Preload("Decorators").Preload("SyncFields").First(entry)
Run Code Online (Sandbox Code Playgroud)

我理解" iDB.Preload("child1").Preload("child2").First(root)"当child1和child2都是root的"leaf"时有效.

所以我的问题是:是否有可能用gorm做到这一点,如果是,那么递归加载comlete层次结构的最佳方法是什么?

谢谢.问候

Jin*_*zhu 9

这已经得到支持,请参阅文档:http://jinzhu.me/gorm/crud.html#nested-preloading

  • 请记住,此实现使用后续的SELECT.虽然这非常简单(并且可能使用正确的回调配置进行多级缓存)......但也可以通过使用`JOIN`语句来优化它,以减少来自多个查询的服务器延迟. (3认同)