Gorm Scan не привязывается к структуре - PullRequest
0 голосов
/ 03 августа 2020

Я хотел бы получить результат сырого 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)

Результат запроса имеет такую ​​структуру 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.

введите описание изображения здесь

1 Ответ

2 голосов
/ 03 августа 2020

Ваши имена полей структуры и имена столбцов не совпадают.

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