简体   繁体   English

如何将 GORM 查询转换为字符串

[英]How to cast GORM query to string

I am writing a web app in go and using the GORM for my ORM. I need to be able to retrieve all the metrics of a certain user and return it via JSON to be displayed on the front end.我正在 go 中编写一个 web 应用程序,并为我的 ORM 使用 GORM。我需要能够检索某个用户的所有指标并通过 JSON 返回它以显示在前端。 The query seems to run successfully but I only see a memory address when printing the results and receive an error when trying to cast the results the standard way.查询似乎运行成功,但在打印结果时我只看到 memory 地址,在尝试以标准方式转换结果时收到错误。 Here is my current code这是我当前的代码

func DisplayData(w http.ResponseWriter, r *http.Request) {
    //Get the data from the database
    var metric models.Metric
    results := db.Where("user_id = ?", "1").Find(&metric)


    //Write a json response
    w.WriteHeader(http.StatusCreated)
    w.Header().Set("Content-Type", "application/json")
    resp := make(map[string]string)
    resp["message"] = results
    jsonResp, err := json.Marshal(resp)
    if err != nil {
        log.Fatalf("Error happened in JSON marshal. Err: %s", err)
    }
    w.Write(jsonResp)
    return
}

This results in the error这导致错误

controllers/statsCont.go:116:18: cannot use results (type *gorm.DB) as type string in assignment
note: module requires Go 1.17

When I try to cast by surrounding result in string() it gives the following error.当我尝试通过 string() 中的周围结果进行转换时,它会出现以下错误。

controllers/statsCont.go:116:26: cannot convert results (type *gorm.DB) to type string
note: module requires Go 1.17

As stated by @BaytaDarell the query result is added in the variable passed inside Find method正如@BaytaDarell 所述,查询结果被添加到Find方法内部传递的变量中

The return value of Find is different in the context it is called in case when it is called with db type the return type is (tx *DB) and when called with associations type the return type is Error Find的返回值在它被调用的上下文中是不同的,当它被调用为 db 类型时,返回类型是(tx *DB)并且当它被调用为 associations 类型时,返回类型是Error

To solve the issue remove below lines要解决此问题,请删除以下行

resp := make(map[string]string)
resp["message"] = results

And update it has并更新它

resp := map[string]interface{}{"message": metric}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM