go version
)?golang 1.8.3
mysql 5.6
Please provide a complete runnable program to reproduce your issue.
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
var db *gorm.DB
func find(v *map[string]interface{}) {
}
func main() {
var err error
db, err = gorm.Open("mysql", "***")
if err != nil {
panic(err)
}
var user map[string]interface{}
db.Debug().Table("test").Find(&user)
fmt.Println(user)
}
Like this demo.I want search some rows from mysql, and I don't want use struct. Beacuse, when I want get a join result, I need to create a new big struct or to payload struct. I think map is good in this.
Any guys can help me ?Thx
You have not initialized the user struct.
Try changing it to var user = make(map[string]interface{})
.
Although I think only structs and slices are allowed.
I don't think it works with maps.
thx @ktsakas . I was tryed your suggest.But it not work. I think you are right, it is only struct or slices.
Maybe this can be of help:
package main
import (
"fmt"
"reflect"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)
type Project struct {
gorm.Model
Name string `gorm:"type:varchar(200)"`
}
func main() {
db, _ := gorm.Open("sqlite3", "db.sqlite3?cache=shared&mode=rwc")
db.AutoMigrate(&Project{})
db.Create(&Project{Name: "A"}) // Demo record inserted
// Now I would like to use reflection to be able to make a generic function
t := reflect.TypeOf(Project{})
fmt.Println(t)
single := reflect.New(t).Interface()
db.Debug().Table("projects").First(single)
fmt.Printf("Single result > %+v\n", single) // Works with a single instance
multiple := reflect.MakeSlice(reflect.SliceOf(t), 0, 10)
db.Debug().Table("projects").Find(&multiple) // Log show table and records are found
fmt.Printf("1. Multiple result > %+v\n", multiple) // But, multiple is empty
// Instead:
// Create a pointer to a slice value and set it to the slice
// multiple := reflect.MakeSlice(reflect.SliceOf(t), 0, 10)
multiplepointer := reflect.New(multiple.Type())
multiplepointer.Elem().Set(multiple)
db.Debug().Table("projects").Find(multiplepointer.Interface())
fmt.Printf("2. Multiple result > %+v\n", multiplepointer) // multiplepointer contains rows
}
Most helpful comment
Maybe this can be of help: