Issue
I’m currently querying a MySql database in GO using gorm. I’m querying a table which i only know its name and nothing else. For this reason I return from the query []map[string]interface{}
, as suggested in gorm documentation (Find To Map, https://gorm.io/docs/advanced_query.html#Find-To-Map).
I have the following problem: query returns right number of element,but are empty map (ex. [map[] map[] map[] map[]]
). I don’t know how to fix this problem, someone could help me to understand what’s wrong?
Thank you.
EDIT
Code example:
db, err := gorm.Open("mysql", "connection_to_my_db")
[...]
var results []map[string]interface{}
err := db.Table("MyTable").Where("condition = ?", id).Find(&results).Error
if err != nil {
return nil, err
}
[...]
Solution
Make sure you are using Gorm V2
Which is the git release tag 1.2. Gorm V1 doesn’t support Find to Map. Check the instructions here on how to upgrade https://gorm.io/docs/v2_release_note.html#How-To-Upgrade
var results []map[string]interface{}
db.Table("MyTable").Where("condition = ?","foo").Find(&results)
// This "pretty" prints it to the console
b, _:= json.MarshalIndent(results, "", " ")
fmt.Println(string(b))
Answered By – Christian
Answer Checked By – David Marino (GoLangFix Volunteer)