2
votes

I'm trying to scan the result of a query into a res structure.

The code builds and the query passes but the result array consists of default values like this:

[{0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0}]

Also, result array has the exact length as the query result should have. When i try generated query in postgres shell it returns the result correctly.

Code:

 type res struct{
    id int
    number int
    user_id int
    }
    
    func getDataJoin(){
        new := []res{}
        db.Db.Table("users").Select("users.id as id, credit_cards.number as number, credit_cards.user_id as user_id").Joins("left join credit_cards on credit_cards.user_id = users.id").Scan(&new)
        fmt.Println("user\n",new)
    }

Generated Query:

SELECT users.id as id, credit_cards.number as number, credit_cards.user_id as user_id FROM "users" left join credit_cards on credit_cards.user_id = users.id

Database result

id | number | user_id 
----+--------+---------
  1 | 1      |       1
  1 | 2      |       1
  2 | 1      |       2
  2 | 2      |       2
  3 | 1      |       3
  3 | 2      |       3
(6 rows)
2

2 Answers

6
votes

Since go-gorm has a certain convention when it comes to naming, you might want to try two things.

Make your res struct publicly available, with public fields:

type Res struct{
    ID int
    Number int
    UserID int
}

Or, specify mappings between columns and fields:

type res struct{
    id int      `gorm:"column:id"`
    number int  `gorm:"column:number"`
    user_id int `gorm:"column:user_id"`
}
0
votes

gorm can only read/write on exported fields much like Marshal/Unmarshal methods of json package. If the first letter of your field is in capital, it will be used. By default, gorm matches struct fields with their camel-cased forms. You can also define your own column names.

Since camel-cased form of both ID and Id, is id, as long as the first letter of your field is in capital, it should work. On a different note, it's good practice to write ID, i.e., both letter capital.