使用Join操作时列名重复导致解析错误

我正在开发一个Gorm用于数据库操作的 Golang 项目。


当我在两个表上执行Join()运算符时,这两个表有两个同名的列 ( id),它运行时没有任何错误或警告,但在使用 解析步骤时出现问题Find(),它显示struct1.id为struct2.id.


在下面的代码中,我试图通过在某些条件下连接两个表来填充两个结构的两个数组。


var array1 []Struct1

var array2 []Struct2


queryRes := gormClient.Model(&Struct1{}).Select("*").

            Joins("Join table 2 on some conditions").

            Where("Other conditions").

            Find(&array1).Find(&array2)


我知道重命名模型的列名或结构标签会有所帮助。但我想知道是否有任何其他解决方案比修改数据库结构更方便。谢谢你,感谢你的帮助。


RISEBY
浏览 183回答 1
1回答

慕勒3428872

此问题已在此线程中提出。贡献者通过创建一个包含两个嵌入式结构的新结构解决了这个问题,如下所示:type Struct1And2 struct {   Struct1   Struct1   `gorm:"embedded"`   Struct2   Struct2   `gorm:"embedded"`}然后执行查询。var struct1and2 []Struct1And2var array1 []Struct1var array2 []Struct2gormClient.Model(&Struct1{}).Select("*").        Joins("Join table 2 on some conditions").        Where("Other conditions").        Find(&struct1and2)// Now we need one more step to build array1 and array2 from struct1and2 separately. 无论如何,我还是希望Gorm将来支持一个一个地扫描结构(就像我在问题中所做的那样),看起来很方便。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go