为了账号安全,请及时绑定邮箱和手机立即绑定

Gorm Scan 未绑定到结构

Gorm Scan 未绑定到结构

Go
潇潇雨雨 2022-06-21 16:05:51
我想获得原始 sql 查询的结果。查询如下res := []response.UserListByDivisionMember{}db.Raw(`SELECT      parentPosFlat.posParentCode AS departmentFlatId,     employee.gsId,     employee.email,     CONCAT(employee.firstname,             ', ',             employee.lastName) AS userName,     division.externalCode AS departmentId,     division.name AS departmentName,     position.code AS positionId,     position.name AS positionName,     gsRoom.name AS room,     gsRoom.id AS roomId FROM     division         JOIN     position AS parentPosition ON division.externalCode = parentPosition.department         JOIN     positionInPositionFlat AS parentPosFlat ON parentPosition.code = parentPosFlat.posParentCode         JOIN     position ON parentPosFlat.posChildCode = position.code         JOIN     employee ON position.code = employee.position         LEFT JOIN     gsRoom ON employee.gsRoomId = gsRoom.id WHERE     division.externalCode = ?`, divisionId).Scan(&res)查询的结果有这个结构 我想将结果绑定到以下结构:type UserListByDivisionMember struct {    DepartmentFlatId string `json:"departmentFlatId"`    GsId             string `json:"gsId"`    Email            string `json:"email"`    UserName         string `json:"userName"`    DepartmentId     string `json:"departmentId"`    DepartmentName   string `json:"departmentName"`    PositionId       string `json:"positionId"`    PositionName     string `json:"positionName"`    Room             string `json:"room"`    RoomId           string `json:"roomId"`}点击查询的扫描操作后,我可以在控制台中看到查询返回了 50 行,这是正确的,但是当我调试应用程序时,结果仅包含结构中的电子邮件地址字段。我已经尝试将名称从小版本更改为大写版本,但仍然显示相同的结果。
查看完整描述

1 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

您的结构字段名称和列名称不匹配。


根据文档:


列名将是字段的名称,小写蛇形。


你有两个选择:


更改 SQL 语句中生成的列名:


parentPosFlat.posParentCode AS department_flat_d,

employee.gsId as gs_id,

...

gsRoom.name AS room,

gsRoom.id AS room_id

或者,使用 struct tags 覆盖列名:


type UserListByDivisionMember struct {

    DepartmentFlatId string `gorm:"column:departmentFlatId"`

    GsId             string `gorm:"column:gsId"`

    ...

    Room             string `gorm:"column:room"`

    RoomId           string `gorm:"column:roomId"`

}


查看完整回答
反对 回复 2022-06-21
  • 1 回答
  • 0 关注
  • 225 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号