首页 > 解决方案 > Go GORM 无法猜测嵌入类型的关系

问题描述

在某些情况下,我需要使用计算数据扩展我的标准模型。例如,在 UI 中显示有关某些 DB 值存在的信息。我通过像这样的类型嵌入创建扩展模型来做到这一点:


/* 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
}

然后我的查询如下所示:

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)

这是我得到的错误:

[error] failed to guess DocumentFulltext's relations with DocumentListEntry's field DocumentFulltext 1 g false

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

我需要如何构建扩展模型才能完成这项工作?

是否推荐这种方法?这里的最佳做法是什么?我应该考虑的任何替代方案?

谢谢!

标签: goormmodelgo-gorm

解决方案


这是 GORM 中的一个错误。已在版本 v0.2.27 中修复。

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


推荐阅读