登录
首页 >  Golang >  Go问答

Gorm Scan 未与模型关联

来源:stackoverflow

时间:2024-02-23 10:30:27 162浏览 收藏

你在学习Golang相关的知识吗?本文《Gorm Scan 未与模型关联》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

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


解决方案


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

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

本篇关于《Gorm Scan 未与模型关联》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>