Search code examples
gogo-gorm

Column name duplicated when use Join operation leading to wrong parsing


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.


Solution

  • 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.