【问题标题】:Scanning into struct of gorm query扫描到 gorm 查询的结构
【发布时间】:2021-06-23 13:03:54
【问题描述】:

我正在尝试将查询结果扫描到 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("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)

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    由于 go-gorm 在命名方面有一定的convention,你可能想尝试两件事。

    使您的 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"`
    }
    

    【讨论】:

    • 它成功了,谢谢你的帮助。将名称更改为 Pascal 大小写有效,但添加 gorm 列标签无效
    • @pariks 如果答案对您有帮助,您可以接受,即使它包含您认为无用的额外信息。
    【解决方案2】:

    gorm 只能在exported fields 上读/写,就像json 包的Marshal/Unmarshal 方法一样。如果您的字段的第一个字母大写,则将使用它。默认情况下,gorm 将结构字段与其驼峰形式匹配。你也可以定义自己的column names

    由于IDId 的驼峰式格式都是id,只要您的字段的第一个字母大写,它应该可以工作。另一方面,最好写ID,即两个字母都大写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多