扫描到gorm查询的结构
我正在尝试将查询结果扫描到 res 结构中。
代码构建并通过查询,但结果数组包含如下默认值:
[{0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0}]
此外,结果数组的长度与查询结果的长度完全相同。当我在 postgres shell 中尝试生成的查询时,它会正确返回结果。
代码:
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("usern",new)
}
生成的查询:
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
数据库结果
id | number | user_id
----+--------+---------
1 | 1 | 1
1 | 2 | 1
2 | 1 | 2
2 | 2 | 2
3 | 1 | 3
3 | 2 | 3
(6 rows)
回答
由于 go-gorm在命名方面有一定的约定,您可能想尝试两件事。
res使用公共字段公开您的结构:
type Res struct{
ID int
Number int
UserID int
}
或者,指定列和字段之间的映射:
type res struct{
id int `gorm:"column:id"`
number int `gorm:"column:number"`
user_id int `gorm:"column:user_id"`
}
- @pariks You can accept the answer if it helped you even if it contains extra information that you found useless.