扫描到Gorm查询的结构体中。

4

我试图将查询结果扫描到一个res结构中。

代码已经编译通过,查询也成功执行,但结果数组却包含了这样的默认值:

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

此外,结果数组的长度与查询结果应该有的长度完全相同。 当我在PostgreSQL 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("user\n",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)
2个回答

9

由于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"`
}

1
它起作用了,谢谢你的帮助。 将名称更改为Pascal case是有效的,但添加gorm列标签没有起作用。 - pariks
2
@pariks 如果答案对您有帮助,即使包含您认为无用的额外信息,也可以接受它。 - sanitizedUser

1

gorm 只能读/写 导出字段,就像 json 包的 Marshal/Unmarshal 方法一样。如果您的字段的第一个字母是大写的,它将被使用。默认情况下,gorm 将结构体字段与其驼峰形式匹配。您还可以定义自己的 列名

由于 IDId 的驼峰形式都是 id,只要您的字段的第一个字母是大写的,它就应该工作。另外,写成 ID,即两个字母都大写,是一个好习惯。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接