go - Go GORM无法猜测嵌入式类型的关系

标签 go orm model go-gorm

在某些情况下,我需要用计算数据扩展我的标准模型。例如。在用户界面中显示有关某些数据库值存在的信息。为此,我可以通过类型嵌入来创建扩展模型,如下所示:


/* 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
我需要如何构建扩展模型才能完成这项工作?
是否完全推荐这种方法?最佳做法是什么?我应该考虑其他选择吗?
谢谢!

最佳答案

这是GORM中的错误。在v0.2.27版中已修复。
GORM问题在这里:https://github.com/go-gorm/gorm/issues/3224

关于go - Go GORM无法猜测嵌入式类型的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63221405/

相关文章:

golang assemble 内存分配

java - 情况下的 Hibernate 映射,其中键也用作多对一参数

mysql - 在本地开发环境中配置 Django 以使用导入的 MySQL 数据库

tensorflow - keras 会自动使用 gpu 吗?

python - Django 无法访问模型中的所有对象

docker - Golang 构建所有下载的包

go - 在 Go 中是否有静态方法来获取当前请求/上下文?

database - 在 gorm orm 上为 golang 中的微服务创建顶级包

c# - NHibernate - 从 sql 函数返回复杂对象

ruby - 不使用 .load() 初始化 Mongoid