Sándor Jankovics
Sándor Jankovics

Reputation: 898

Gorm Scan not getting bound to struct

I would like to get the result of a raw sql query. The query is the following

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)

The result of the query has this structure enter image description here

I would like to bind the results to the following struct:

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

After hitting the scan operation of the query I can see in the console that the query has 50 rows returned which is correct, but when I am debugging the application the result contains only the email address field from the struct. I have tried already changing the names from small to captial version but still the same result is shown.

enter image description here

Upvotes: 1

Views: 2867

Answers (1)

Marc
Marc

Reputation: 21055

Your struct field names and column names do not match.

Per the docs:

Column names will be the field’s name is lower snake case.

You have two options:

Change the generated column names in the SQL statement:

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

Or, override the column name using 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"`
}

Upvotes: 5

Related Questions