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,
...此处省略
}
来源:oschina
链接:https://my.oschina.net/u/2007165/blog/4263403