首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GORM :在两个关系方向上预加载是可能的吗?

GORM :在两个关系方向上预加载是可能的吗?
EN

Stack Overflow用户
提问于 2020-08-02 22:40:51
回答 1查看 105关注 0票数 0

我想知道是否可以从关系的两端预加载数据。考虑这个例子:

代码语言:javascript
复制
type User struct {
    gorm.Model
    Name      string
    Documents []Document // has-many
}
type Document struct {
    gorm.Model
    UserID           uint
    Name             string
    DocumentFulltext DocumentFulltext // has-one
}
type DocumentFulltext struct {
    gorm.Model
    DocumentID uint
    Name       string
}

这样,我就可以轻松地获得任何给定文档的DocumentFulltext,如下所示

代码语言:javascript
复制
db.Where("id = ?", ID).Preload("DocumentFulltext").Find(&document)

成功了!

但是,如果我拥有文档并希望预加载(或加入)它所属的用户,该怎么办呢?

代码语言:javascript
复制
db.Where("id = ?", ID).Preload("User").Find(&document)

这让我很恐慌。(invalid memory address)

代码语言:javascript
复制
db.Where("id = ?", ID).Joins("User").Find(&document)

这就产生了像.... FROM "documents" User WHERE id = ...这样不可靠的SQL。

这怎麽可能?我需要使用“手动”查询吗?

--

如果不可能:什么是好的实践/指导方针?如何对我的关系建模,以便我可以有效地使用.Preload()等GORM内置组件?

例如,如果我将用户和文档之间的关系如下所示:

代码语言:javascript
复制
type User struct {
    gorm.Model
    Name string
}
type Document struct {
    gorm.Model
    User             User // belongs-to
    UserID           uint
    Name             string
    DocumentFulltext DocumentFulltext // has-one
}
type DocumentFulltext struct {
    gorm.Model
    DocumentID uint
    Name       string
}

然后,我可以为任何给定的文档预加载DocumentFulltext和User。但是如果我想为一个给定的用户做这件事,我就失去了预加载文档和全文的能力。

--

任何提示,我们将不胜感激。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-02 23:15:34

使用关系两边表示Document结构中的UserUser结构中的Documents

代码语言:javascript
复制
type User struct {
    gorm.Model
    Name      string
    Documents []Document // has-many
}

type Document struct {
    gorm.Model
    UseredID uint
    Name     string
    User   User
}

然后,您可以预加载两端

代码语言:javascript
复制
db.Debug().Where("id = ?", ID).Preload("User").Find(&document)
db.Debug().Where("id = ?", ID).Preload("Documents").Find(&user)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63217295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档