Your Question
I'm trying to batch insert data from a map into a sqlite database following the example on documentation. https://gorm.io/docs/create.html#Create-From-Map
However, whenever I run this code I get the following error.
package main
import (
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func main() {
type User struct {
gorm.Model
Name string
Age int
Birthday time.Time
}
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("Error")
}
db.AutoMigrate(&User{})
// batch insert from `[]map[string]interface{}{}`
db.Model(&User{}).Create([]map[string]interface{}{
{"Name": "jinzhu_1", "Age": 18},
{"Name": "jinzhu_2", "Age": 20},
})
}
Error:
sql: Scan error on column index 0, name "id": unsupported Scan, storing driver.Value type int64 into type *map[string]interface {}
[rows:2] INSERT INTO `users` (`age`,`name`) VALUES (18,"jinzhu_1"),(20,"jinzhu_2") RETURNING `id`
In the same way, if I define the User type with an ID or a variable in capital letters (UID, AID, ...), the code throws the same error.
...
type User struct {
ID uint `gorm:"primaryKey"`
Name string
Age int
Birthday time.Time
}
...
or
...
type User struct {
UID uint `gorm:"primaryKey"`
Name string
Age int
Birthday time.Time
}
...
However, if I define the User type without the gorm.Model or if I define the id with another name, for example userid (starting with small letter), the code works.
...
type User struct {
Name string
Age int
Birthday time.Time
}
...
or
...
type User struct {
userID uint `gorm:"primaryKey"`
Name string
Age int
Birthday time.Time
}
...
Is this an expected behavior?
The document you expected this should be explained
https://gorm.io/docs/create.html#Create-From-Map
Expected answer
I would appreciate if someone could verify if this is an expected behavior or could be an issue.
Comment From: a631807682
This is an error related to returning, which is used to write back to the param, and the error caused by passing unaddressable value
- db.Model(&User{}).Create([]map[string]interface{}{
+ db.Model(&User{}).Create(&[]map[string]interface{}{
{"Name": "jinzhu_1", "Age": 18},
{"Name": "jinzhu_2", "Age": 20},
})