GORM Model and Table function

Viewed 292

I'm still learning about go and gorm, and following the tutorial from the gorm page itself (https://gorm.io/docs/advanced_query.html). It is stated that results from Find and First can be stored in map[string]interface{} or []map[string]interface{}. However, upon testing this functionality it doesn't seem to work:

package main

import (
    "fmt"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

const (
    dbtech = "sqlite3"
    dbname = "test.db"
)

var db *gorm.DB
var err error

type TestStruct struct {
    Name string
}

func main() {
    db, err = gorm.Open(dbtech, dbname)
    defer db.Close()
    db.AutoMigrate(&TestStruct{})

    db.Create(&TestStruct{Name: "Alice"})
    db.Create(&TestStruct{Name: "Bob"})

    structResults := []TestStruct{}
    db.Find(&structResults)
    fmt.Println(structResults)

    var mapResult map[string]interface{}
    db.Model(&TestStruct{}).First(&mapResult)
    for k, v := range mapResult {
        fmt.Println(k, " - ", v)
    }
    fmt.Println(mapResult)

    var mapResults []map[string]interface{}
    db.Model(&TestStruct{}).Find(&mapResults)
    for k, v := range mapResult {
        fmt.Println(k, " - ", v)
    }
    fmt.Println(mapResult)
}

and the output is:

[{Alice} {Bob}]
map[]
map[]

Am I doing something wrong? Or does this feature is no longer available?

EDIT: It is not working both with Model() and Table() functions.

1 Answers

I noticed that you are browsing the Gorm V2 docs, but are importing the Gorm V1.

You should change your imports to:

"gorm.io/gorm"
_ "gorm.io/driver/sqlite"

This will make the code work as expected.

If you can't upgrade the Gorm version, you'll have to store the results on a struct or slice of structs.

Related