我有一个由几个结构组成的层次结构
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
}
我的数据库创建定义如下:
db.CreateTable(&Entry{})
db.CreateTable(&SyncField{})
db.Model(&Entry{}).Related(&SyncField{}, "EntryId")
db.CreateTable(&Decorator{})
db.Model(&SyncField{}).Related(&Decorator{}, "DecoratorId")
一切都很清楚,并且可以正常预加载这样的层次结构中的一个“子级别”:
entry := &Entry{Id: i}
iDB.Preload("SyncFields").First(entry)
要么
field := &SyncField{Id: idf}
iDB.Preload("Decorators").First(field)
我正在寻找一种方法,使用GORM预加载整个层次,在其中一个根元素上调用“First()”方法...我想加载一个“条目”及其所有相关的“字段”,我也想要让每个“Field”预装所有“装饰者”......
使用几个“Preload()”函数是不可行的:
entry := &Entry{Id: i}
iDB.Preload("Decorators").Preload("SyncFields").First(entry)
我理解root的“ iDB.Preload("child1").Preload("child2").First(root)
" works when both child1 and child2 are " leaf” .
所以我的问题是:是否有可能用gorm做到这一点,如果是,那么递归加载comlete层次结构的最佳方法是什么?
谢谢 . 问候
3 回答
这已经得到支持,请参阅文档:http://jinzhu.me/gorm/crud.html#nested-preloading
我的解决方案
不,这是不可能的 . 这是一个尚未实现的请求功能:
https://github.com/jinzhu/gorm/issues/392