首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Go GORM未能猜测嵌入式类型的关系

Go GORM未能猜测嵌入式类型的关系
EN

Stack Overflow用户
提问于 2020-08-02 21:55:24
回答 1查看 334关注 0票数 0

在某些情况下,我需要用计算数据扩展我的标准模型。例如,显示UI中存在一些DB值的信息。为此,我通过类型嵌入创建一个扩展模型,如下所示:

代码语言:javascript
复制
/* Standard Models */

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

type Document struct {
    gorm.Model
    User             *User // belongs-to
    UserID           uint
    Name             string
    DocumentFulltext *DocumentFulltext // has-one
}

type DocumentFulltext struct {
    gorm.Model
    Document   *Document // belongs-to
    DocumentID uint 
    Fulltext   string
}

/* Extensions */

type DocumentListEntry struct {
    Document       `gorm:"embedded"`
    FulltextExists bool
}

然后,我的查询如下:

代码语言:javascript
复制
queryConnection := DBConnection
queryConnection = queryConnection.Joins("left join document_fulltexts on documents.id = document_fulltexts.document_id")
queryConnection = queryConnection.Where(`"documents"."user_id" = ?`, userID)
queryConnection = queryConnection.Select(
    `"documents"."user_id",
    "documents"."name",
    CASE WHEN "document_fulltexts"."fulltext" IS NOT NULL THEN TRUE ELSE FALSE END AS "fulltext_exists"`,
)
documents := []DocumentListEntry{}
queryConnection.Table("documents").Scan(&documents)

这是我得到的错误:

代码语言:javascript
复制
[error] failed to guess DocumentFulltext's relations with DocumentListEntry's field DocumentFulltext 1 g false

在这里可以找到完整的演示:https://github.com/go-gorm/playground/pull/62

我需要如何构建扩展的模型来实现这个工作呢?

是否建议采用这种方法?这里的最佳做法是什么?有什么可供选择的吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-04 21:03:37

这是戈姆的一个窃听器。修正了版本0.2.27。

GORM问题:https://github.com/go-gorm/gorm/issues/3224

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63221405

复制
相关文章

相似问题

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