如何使用GORM在GO中预加载完整的层次结构 [英] how preload a full hierarchy in GO using GORM

查看:280
本文介绍了如何使用GORM在GO中预加载完整的层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a hierachy composed by several structures

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
}

我的数据库创建是这样定义的:

My DB creation is definded like this :

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

db.CreateTable(&Decorator{})
db.Model(&SyncField{}).Related(&Decorator{}, "DecoratorId")

一切都很清楚,并且可以很好地预加载一个"sub level"子对象.这样的层次结构:

Everything is clear and works fine to preload just one "sub level" of the hierachy like this :

entry := &Entry{Id: i}
iDB.Preload("SyncFields").First(entry)

field := &SyncField{Id: idf}
iDB.Preload("Decorators").First(field)

我正在寻找一种使用GORM来预先加载整个层次结构的方法,以调用"First()"根元素之一上的方法...我想加载一个条目"及其所有相关的字段"而且我也想拥有每个字段"预装了所有装饰器" ...

I'm looking for a way using GORM to preload the whole hierachy invoking the "First()" method on one of the root element... I want to load an "Entry" with all its related "Fields" and I also want to have each "Field" preloaded with all its "Decorators"...

使用多个"Preload()"是不可行的.功能:

This is not feasable using the several "Preload()" functions :

entry := &Entry{Id: i}
iDB.Preload("Decorators").Preload("SyncFields").First(entry)

我了解" iDB.Preload("child1").Preload("child2").First(root)"当child1和child2都为叶子"时,它起作用.的根.

I understand "iDB.Preload("child1").Preload("child2").First(root)" works when both child1 and child2 are "leaf" of root.

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

So my question is : is it possible to do this with gorm and if yes what is the best way to load recursively a complete hierachy?

谢谢.问候

推荐答案

已支持此功能,请参阅文档:

This is already supported, please refer to the documentation: http://jinzhu.me/gorm/crud.html#nested-preloading

这篇关于如何使用GORM在GO中预加载完整的层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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