Your Question

I read the doc here https://gorm.io/docs/create.html#Create-From-Map and find that gorm can use Create From Map feature, for example

db.Model(&User{}).Create(map[string]interface{}{  "Name": "jinzhu", "Age": 18})

But how to get the insert id after create from map?

The document you expected this should be explained

https://gorm.io/docs/create.html#Create-From-Map

Expected answer

How to get inserted id when using Create From Map

Comment From: ghost

@stormeyes hello, this fllowing code :

type User struct {
    Id   int64  `gorm:"primaryKey;autoIncrement"`
    Name string `gorm:"column:name;"`
    Age  int64  `gorm:"column:age"`
}

func Find() error {
    //var users []*User
    db := GetDBConnection()
    db.Debug().Model(&User{}).Create(map[string]interface{}{"name": "jinzhu", "age": 18, "id": 1})
    return nil
}

run result

[0.161ms] [rows:1] INSERT INTO `users` (`age`,`id`,`name`) VALUES (18,1,"jinzhu")

sorry , there should be no way to backfill primary key when you use map to insert

Comment From: stormeyes

@longlihale Great job and thank u :)

Comment From: qcoh

I have the same issue and for the problem I'm trying to solve, I do not know the schema of the database before compiling (i.e. in my situation, the above User struct does not exist). I would like to be able to create a row from a map and return the primary key in my API's response.

Does anyone know a workaround for doing this?

Comment From: karlspace7

you can use "db.Clauses()" like this: db.Debug().Clauses(clause.Returning{Columns: []clause.Column{{Name: "id"}}}).Table("test_table").Create(record1) // INSERT INTO "test_table" ("length","name1") VALUES (11,'name11') RETURNING "id"