英文:
Column name duplicated when use Join operation leading to wrong parsing
问题
我正在使用Gorm
在一个Golang项目中进行数据库操作。
当我在两个具有相同名称(id
)的列的表上执行Join()
操作时,它可以正常运行,没有任何错误或警告,但在解析步骤中使用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)
我知道重命名列名或模型的结构标签会有所帮助。但我想知道是否有其他比修改数据库结构更方便的解决方案。谢谢你,感谢你的帮助。
英文:
I am working on a Golang project using Gorm
for database manipulations.
When I perform a Join()
operator on two tables that have two columns with the same name (id
), it runs without any error or warning but there's a problem in parsing step with Find()
, it reads struct1.id
as struct2.id
.
In following code, Im trying to fill the two arrays of two structs by joining two tables on some conditions.
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)
I know that renaming the column names or struct tags of the models will help. But I wonder if there is any other solution being more convenient than modifying database structs. Thank you and appreciate your helps.
答案1
得分: 0
这个问题在这个线程中提出。贡献者通过创建一个包含两个嵌入结构的新结构来解决这个问题,类似以下的方式:
type Struct1And2 struct {
Struct1 Struct1 `gorm:"embedded"`
Struct2 Struct2 `gorm:"embedded"`
}
然后执行查询操作。
var struct1and2 []Struct1And2
var array1 []Struct1
var array2 []Struct2
gormClient.Model(&Struct1{}).Select("*").
Joins("Join table 2 on some conditions").
Where("Other conditions").
Find(&struct1and2)
// 现在我们需要再进行一步操作,从struct1and2中分别构建array1和array2。
无论如何,我仍然希望Gorm
在将来能够支持逐个扫描结构体(就像我在问题中所做的那样),这看起来很方便。
英文:
This issue has been raised in this thread. The contributor solved this by creating a new struct containing two embedded structs, something likes following:
type Struct1And2 struct {
Struct1 Struct1 `gorm:"embedded"`
Struct2 Struct2 `gorm:"embedded"`
}
Then perform a query.
var struct1and2 []Struct1And2
var array1 []Struct1
var array2 []Struct2
gormClient.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.
Anyway, I still hope Gorm
support scanning structs one by one in future (like the way i did in my question), it looks convenient.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论