how preload a full hierarchy in GO using GORM

Guillaume Barré picture Guillaume Barré · Mar 24, 2015 · Viewed 16.4k times · Source

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 complete hierachy?

Thanks. Regards

Answer

Jinzhu picture Jinzhu · May 13, 2015

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