Home > Software engineering >  Get all data from a table in golang gorm
Get all data from a table in golang gorm

Time:06-14

I'm new in golang and programming at all, so I've a problem with this function that supposed gets it all values from a table, but just shows me one. Thanks you all for your knowledge :)

func GetAll(w http.ResponseWriter, r *http.Request) {
    results := map[string]interface{}{}
    c, _ := connection.GetDB()
    c.Table("products").Order("id_producto asc").Find(&results)
    fmt.Print(results)
    jsonString, _ := json.Marshal(results)
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprint(w, string(jsonString))

}

CodePudding user response:

Try to create a DTO struct and create a list that contains item of type that struct. Then pass that list to the query. Like this:

type Product struct {
   ProductID string
}
func GetAll(w http.ResponseWriter, r *http.Request) {
   products := []*Product{}
   c, _ := connection.GetDB()
   c.Order("id_producto asc").Find(&products).
   jsonString, _ := json.Marshal(products)
   w.Header().Set("Content-Type", "application/json")
   fmt.Fprint(w, string(jsonString))

}

CodePudding user response:

You can code like this:

func GetAll(w http.ResponseWriter, r *http.Request) {
    // New a slice to get the results,
    // map[string]interface{}{} will only scan one item of results
    results := []map[string]interface{}{}
    c, _ := connection.GetDB()
    c.Table("products").Order("id_producto asc").Find(&results)
    fmt.Print(results)
    jsonString, _ := json.Marshal(results)
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprint(w, string(jsonString))

}
  • Related