go - 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
我需要如何构建扩展模型才能完成这项工作?
是否推荐这种方法?这里的最佳做法是什么?我应该考虑的任何替代方案?
谢谢!
解决方案
这是 GORM 中的一个错误。已在版本 v0.2.27 中修复。
GORM 问题在这里:https ://github.com/go-gorm/gorm/issues/3224
推荐阅读
- angularjs - 在 AngularJS 中动态更改选项值时,选择选项未正确反映
- perl - DateTime::Event::Cron::Quartz 无法处理 */2 小时
- google-maps - 如何在离子原生谷歌地图中将折线适合屏幕内
- ruby-on-rails - 如何使用 CoffeeScript 在 Rails 模板中显示 div?
- go - 使用包将字符串从一种格式转换为另一种格式
- git - 通过拉取请求从主分支中删除提交
- android - Android RTL 设计中的本地化
- java - 如何在 Java 中以树状结构显示列表数据?
- r - R metafor - 为什么使用默认权重与将权重设置为 1/方差时结果不同?
- python - 按连续字长创建字典