使用连接操作时,列名重复导致解析错误。

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年7月11日 17:57:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72936719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定