鍍金池/ 問答/GO  網(wǎng)絡(luò)安全/ Golang gorm 關(guān)聯(lián)數(shù)據(jù)不存在時(shí)如何返回Null?

Golang gorm 關(guān)聯(lián)數(shù)據(jù)不存在時(shí)如何返回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時(shí),LastReplyUser 應(yīng)該是不存在的,則查詢后返回的 LastReplyUser 如何為一個(gè)null,或者說是nil

目前的查詢出來轉(zhuǎn)化為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,
        ...此處省略
    }

如何能的得到這樣的結(jié)構(gòu) :

     {
       ...此處省略
        "last_reply_user":null, # 或者 {}
        "last_reply_user_id": 0,
        ...此處省略
    }
回答
編輯回答
獨(dú)白

LastReplyUser User
改成
LastReplyUser *User
go里的結(jié)構(gòu)體零值不是nil,指針才是

2018年7月13日 22:14