go - 未加载时如何忽略JSON输出中的关联字段?

标签 go model go-gorm go-gin

在我的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()配置文件,也仍然有一个空集:
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响应中的Profile字段?为了节省一些转让费用

最佳答案

如果要忽略它们,则应使用该结构的指针。如果未加载,它将变为nil,并且不会出现在JSON中

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

    Profile *Profile `json:",omitempty"`
}

关于go - 未加载时如何忽略JSON输出中的关联字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61609409/

相关文章:

go - 如何在Go子目录中构建程序?

go - 如何检查 URL 参数是否存在

java - MVC - 如何将数据从 View 传递到 Controller

postgresql - postgres 抛出错误 : null value in column "id" violates not-null constraint even when value is actually not null

mysql - golang gorm 访问底层mysql查询

go - RegExp.MatchString 是线程安全的吗?

go - golang中指针内容的差异

go - 如何正确定义 gorm 数据库接口(interface)?

ruby-on-rails - ruby on rails 模型中的全局方法

java - 从 JSON 格式的服务器响应获取 token