Golang gorm 关联数据不存在时如何返回Null

邮差的信 提交于 2020-05-03 16:37:46

Golang gorm 关联数据不存在时如何返回Null?

这是model

type Topic struct {
    BaseModel
    User            User           `json:"user" gorm:"ForeignKey:UserId"`
    UserId          int            `json:"user_id"`
    Category        Category       `json:"category" `
    CategoryId      int            `json:"category_id"`
    Title           string         `json:"title"`
    Cover           string         `json:"cover"`
    Content         string         `json:"content"`
    LastReplyUser   User           `json:"last_reply_user" gorm:"ForeignKey:LastReplyUserId"`
    LastReplyUserId int            `json:"last_reply_user_id"`
    LastReplyAt     mysql.NullTime `json:"last_reply_at"`
    ViewCount       int            `json:"view_count"`
    LikeCount       int            `json:"like_count"`
    IsRecommended   int            `json:"is_recommended"`
    IsTop           int            `json:"is_top"`
    Status          int            `json:"status"`
    Sort            int            `json:"sort"`
}

Topic Belong to User, Category, LastReplyUser

比如 LastReplyUserId 为0时,LastReplyUser 应该是不存在的,则查询后返回的 LastReplyUser 如何为一个null,或者说是nil

目前的查询出来转化为json的效果如下 :

     {
       ...此处省略
        "last_reply_user": {
            "id": 0,
            "created_at": "0001-01-01T00:00:00Z",
            "updated_at": "0001-01-01T00:00:00Z",
            "username": "",
            "email": "",
            "phone": "",
            "last_login_at": {
                "Time": "0001-01-01T00:00:00Z",
                "Valid": false
            },
            "post_count": 0,
            "topic_count": 0,
            "status": 0,
            "follower_count": 0,
            "following_count": 0
        },
        "last_reply_user_id": 0,
        ...此处省略
    }

如何能的得到这样的结构 :

     {
       ...此处省略
        "last_reply_user":null, # 或者 {}
        "last_reply_user_id": 0,
        ...此处省略
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!