create with schema map return pk

This commit is contained in:
方圣卿 2023-11-07 21:53:45 +08:00
parent bccc8fdf1e
commit 161be61b3d

View File

@ -153,7 +153,8 @@ func Create(config *Config) func(db *gorm.DB) {
db.AddError(db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.Context, db.Statement.ReflectValue, insertID)) db.AddError(db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.Context, db.Statement.ReflectValue, insertID))
} }
} }
} else if db.Statement.Dest != nil { }
if db.Statement.Dest != nil {
// append @id column with value for auto-increment primary key // append @id column with value for auto-increment primary key
// the @id value is correct, when: 1. without setting auto-increment primary key, 2. database AutoIncrementIncrement = 1 // the @id value is correct, when: 1. without setting auto-increment primary key, 2. database AutoIncrementIncrement = 1
insertID, err := result.LastInsertId() insertID, err := result.LastInsertId()
@ -163,11 +164,16 @@ func Create(config *Config) func(db *gorm.DB) {
return return
} }
pkFieldName := "@id"
if db.Statement.Schema != nil && db.Statement.Schema.PrioritizedPrimaryField != nil {
pkFieldName = db.Statement.Schema.PrioritizedPrimaryField.DBName
}
switch values := db.Statement.Dest.(type) { switch values := db.Statement.Dest.(type) {
case map[string]interface{}: case map[string]interface{}:
values["@id"] = insertID values[pkFieldName] = insertID
case *map[string]interface{}: case *map[string]interface{}:
(*values)["@id"] = insertID (*values)[pkFieldName] = insertID
case []map[string]interface{}, *[]map[string]interface{}: case []map[string]interface{}, *[]map[string]interface{}:
mapValues, ok := values.([]map[string]interface{}) mapValues, ok := values.([]map[string]interface{})
if !ok { if !ok {
@ -179,7 +185,7 @@ func Create(config *Config) func(db *gorm.DB) {
} }
for _, mapValue := range mapValues { for _, mapValue := range mapValues {
if mapValue != nil { if mapValue != nil {
mapValue["@id"] = insertID mapValue[pkFieldName] = insertID
} }
insertID += schema.DefaultAutoIncrementIncrement insertID += schema.DefaultAutoIncrementIncrement
} }