I’ve been learning GORM from the official docs, and I’m running into some confusion when trying to create records from a map using the Create() function.
The official documentation shows this example for creating records from a map:
// Single insert
db.Model(&User{}).Create(map[string]interface{}{
"Name": "jinzhu", "Age": 18,
})
// Batch insert
db.Model(&User{}).Create([]map[string]interface{}{
{"Name": "jinzhu_1", "Age": 18},
{"Name": "jinzhu_2", "Age": 20},
})
But here’s the thing — this works fine if there is no primary key (PK) defined for the table. However, if I define a PK field (like user_id), I get an error. From what I understand, every table must have a primary key for normalization, so why does this method work without a PK?
Is there any valid use case for creating records from a map if the table has a PK? Does GORM handle PKs automatically in this case? Or is there something I’m missing, and it really doesn’t work with PKs?
I’m also wondering if the example in the docs is actually well-written or if it needs a correction for handling tables with primary keys. Should I be using structs instead of maps when working with tables that have a PK?