我想獲得原始 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"`
}
- 1 回答
- 0 關注
- 172 瀏覽
添加回答
舉報
0/150
提交
取消