duanli8391
2018-12-07 14:02
浏览 445
已采纳

当找不到值时,Gorm返回空对象,而不是默认对象

I made a MySQL query using GORM inside a little go app.

I have declared my domain struct

type Domain struct {
    gorm.Model
    Name string
    ...
}

Then when I send a query to MySQL with GORM with this method.

func DomainInfos(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    w.WriteHeader(http.StatusOK)

    var d Domain

    config.DbConnection.Where("name = ?", vars["domain"]).Find(&d)

    json.NewEncoder(w).Encode(d)
}

When the domain is not found it return an default object from my struct definition

{
    {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} 
    0
    0
    0
}

So I wrote a little condition to manually return an empty object

if d.ID == 0 {
    json.NewEncoder(w).Encode(make(map[string]string))
    return
}

Is it possible GORM return an empty object directly when the query return nothing, to avoid this manual checking ?

1条回答 默认 最新

相关推荐 更多相似问题