【问题标题】:How to ignore an association field in JSON output when it is not loaded?未加载时如何忽略 JSON 输出中的关联字段?
【发布时间】:2020-08-19 21:26:34
【问题描述】:

在我的 gorm 模型中,我有用户和个人资料:

type User struct {
    ID            int    
    Username      string
    Password      string     `json:"-"`

    Profile Profile
}

type Profile struct {
    UserID        int    
    Gender        string
    Places        string

    //...And many more fields
}

当我通过以下方式查找个人资料的完整显示时:

db.Preload("Profile").Where("id = ?", 1).First(&user)
c.JSON(200, user) 

客户端将收到的 JSON 结果非常好:

{
    "ID": 1,
    "Username": {
        "String": "",
        "Valid": false
    },
    "Profile": {
        "UserID": 1,
        "Gender": "men",
        "Places": "Home and staying home",
        // ...And many more
    },
}

但是当我只想列出 ID 和 Username 两个字段时,即使我没有 Preload() 或 Related() Profile,它仍然是一个空集:

db.Where("id = ?", 1).First(&user)
c.JSON(200, user) 

// Result
{
    "ID": 1,
    "Username": {
        "String": "",
        "Valid": false
    },
    //below is redundant in this situation
    "Profile": {
        "UserID": 0,
        "Gender": "",
        "Places": "",
        // ...And many more 0 or "" fields
    },
}

我的问题是如何在每次未加载 JSON 响应时忽略配置文件字段?为了节省一些转账费用

【问题讨论】:

    标签: go model go-gorm go-gin


    【解决方案1】:

    如果你想省略它们,你应该使用结构的指针。如果没有加载,它将使其为零,并且不会出现在 JSON 中

    type User struct {
        ID            int    
        Username      string
        Password      string     `json:"-"`
    
        Profile *Profile `json:",omitempty"`
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      相关资源
      最近更新 更多