如何在未加载json输出时忽略关联字段?

问题描述 投票:0回答:1

在我的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字段?以节省一些转移成本

go model gorm gin
1个回答
0
投票

如果要忽略它们,则应使用该结构的指针。

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

    Profile *Profile `json:",omitempty"`
}
© www.soinside.com 2019 - 2024. All rights reserved.