doubi1931 2019-09-01 02:56
浏览 174
已采纳

如何使查询结果结构与我在GORM Select上声明的内容匹配

I want to make the structure of the query results match what I have stated in GORM Select because right now it only matches the Struct structure. How do i make it work? Thank you in advance

i've tried to make new Struct and it works, but i dont know is it a best practice or not

type User struct {
    User_Id  uint   `json:"user_id" gorm:"column:user_id; PRIMARY_KEY"`
    Email    string `json:"email"`
    Password string `json:"password"`
    Token    string `json:"token" gorm:"-"`
}

func GetUsers() map[string]interface{} {
    users := []User{}
    GetDB().Table("app_user").Select("user_id, email").Find(&users)
    resp := u.Message(true, "All users")
    resp["users"] = users
    return resp
}
//actual result
{
    "message": "All users",
    "status": true,
    "users": [
        {
            "user_id": 1732,
            "email": "aaaaaaa@gmail.com",
            "password": "",
            "token": ""
        },
        {
            "user_id": 1733,
            "email": "bbbbbbb@gmail.com",
            "password": "",
            "token": ""
        },
    ]
}

//Expected result 
{
    "message": "All users",
    "status": true,
    "users": [
        {
            "user_id": 1732,
            "email": "aaaaaaa@gmail.com"
        },
        {
            "user_id": 1733,
            "email": "bbbbbbb@gmail.com"
        }
     ]
}
  • 写回答

1条回答 默认 最新

  • duanliao2310 2019-09-01 03:00
    关注

    It looks like all you need to do is to omit empty fields. You can do that by adding omitempty to json tags:

        Password string `json:"password,omitempty"`
        Token    string `json:"token,omitempty" gorm:"-"`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#web项目#的问题,请各位专家解答!
  • ¥15 vmtools环境不正常
  • ¥15 请问如何在Ubuntu系统中安装使用microsoft R open?
  • ¥15 jupyter notebook
  • ¥30 informer时间序列预测
  • ¥20 SSR引物多态性分析
  • ¥15 大漠插件在Win11易语言注册调用和免注册灵异事件,VS上注册调用完全没问题
  • ¥15 Addressable缓存机制做热更新的问题
  • ¥15 微信开发者工具vant组件
  • ¥15 iPhone iCloud云盘资料删除,MAC丢失50多G桌面资料