简体   繁体   English

GORM ORM:可以在两个关系方向上预加载吗?

[英]GORM ORM: Preloading in both relationship directions possible?

I would like to know if it is possible to preload data from both sides of a relationship.我想知道是否可以从关系的双方预加载数据。 Consider this example:考虑这个例子:

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
}

With that I can easily get the DocumentFulltext for any given document like this有了它,我可以轻松获取任何给定文档的 DocumentFulltext 像这样

db.Where("id = ?", ID).Preload("DocumentFulltext").Find(&document)

Works!作品!

But what if I have the document and want to preload (or join) the User it belongs to?但是,如果我有文档并想要预加载(或加入)它所属的用户怎么办?

db.Where("id = ?", ID).Preload("User").Find(&document)

That gives me a panic.这让我感到恐慌。 ( invalid memory address ) invalid memory address

db.Where("id = ?", ID).Joins("User").Find(&document)

And that produces wonky SQL like .... FROM "documents" User WHERE id =...这会产生不稳定的 SQL ,例如.... FROM "documents" User WHERE id =...

How is this possible?这怎么可能? Do I need to use "manual" queries?我需要使用“手动”查询吗?

-- --

If it is not possible: what is a good-practice / guideline how to model my relationships so I can use GORM built-ins like.Preload() effectively?如果不可能:什么是良好实践/指南如何 model 我的关系,以便我可以有效地使用 GORM 内置插件 like.Preload()?

Eg If I put the relationship between Users and Documents like this:例如,如果我将用户和文档之间的关系如下:

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
}

then I can preload both, DocumentFulltext AND User, for any given Document.然后我可以为任何给定的文档预加载 DocumentFulltext 和 User。 But I loose the ability the preload Documents and Fulltexts if I want to do it for a given User.但是如果我想为给定的用户做预加载文档和全文的能力,我会失去它。

-- --

Any hints a re appreciated.任何提示都值得赞赏。 Thx!谢谢!

Use relation both side means User in Document struct and Documents in User struct使用关系双方意味着Document结构中的UserUser结构中的Documents

type User struct {
    gorm.Model
    Name      string
    Documents []Document // has-many
}

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

Then you can preload both sides然后你可以预加载双方

db.Debug().Where("id = ?", ID).Preload("User").Find(&document)
db.Debug().Where("id = ?", ID).Preload("Documents").Find(&user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM