duanheyi7147 2015-03-24 10:32
浏览 299
已采纳

如何使用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")

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)

or

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

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"...

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

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

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

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

Thanks. Regards

  • 写回答

2条回答 默认 最新

  • dongzhonggua4229 2015-05-13 01:53
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题