Go GORM 无法猜测嵌入式类型的关系
Go GORM failed to guess relations for embedded types
在某些情况下,我需要使用计算数据扩展我的标准模型。例如。显示有关 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
我需要如何构建扩展模型才能完成这项工作?
完全推荐这种方法吗?这里的最佳实践是什么?我应该考虑其他选择吗?
谢谢!
这是 GORM 中的错误。已在版本 v0.2.27 中修复。
GORM 问题在这里:https://github.com/go-gorm/gorm/issues/3224
在某些情况下,我需要使用计算数据扩展我的标准模型。例如。显示有关 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
我需要如何构建扩展模型才能完成这项工作?
完全推荐这种方法吗?这里的最佳实践是什么?我应该考虑其他选择吗?
谢谢!
这是 GORM 中的错误。已在版本 v0.2.27 中修复。
GORM 问题在这里:https://github.com/go-gorm/gorm/issues/3224