mysqlgogo-gorm

GORM empty Find to Map


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).

I have the following problem: query returns right number of element, but the map is empty (e.g. [map[] map[] map[] map[]]). I don't know how to fix this problem, someone could help me to understand what's wrong?

Thank you.


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

    GORM V1 doesn't support "Find to Map". Check the instructions here on 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))