【问题标题】:Gorm Scan not getting bound to structGorm Scan 未绑定到结构
【发布时间】:2020-08-03 18:05:30
【问题描述】:

我想获得原始 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 行,这是正确的,但是当我调试应用程序时,结果仅包含结构中的电子邮件地址字段。 我已经尝试将名称从小版本更改为大写版本,但仍然显示相同的结果。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

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

    每the docs:

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

    你有两个选择:

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

    parentPosFlat.posParentCode AS department_flat_d,
    employee.gsId as gs_id,
    ...
    gsRoom.name AS room,
    gsRoom.id AS room_id
    

    或者,使用结构标签覆盖列名:

    type UserListByDivisionMember struct {
        DepartmentFlatId string `gorm:"column:departmentFlatId"`
        GsId             string `gorm:"column:gsId"`
        ...
        Room             string `gorm:"column:room"`
        RoomId           string `gorm:"column:roomId"`
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 2021-07-05
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多