Skip to content

Commit

Permalink
create with schema map return pk
Browse files Browse the repository at this point in the history
  • Loading branch information
方圣卿 committed Nov 8, 2023
1 parent 60d6939 commit 9dd2821
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions callbacks/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}
} else if db.Statement.Dest != nil {
}
if db.Statement.Dest != nil {
// 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
insertID, err := result.LastInsertId()
Expand All @@ -163,11 +164,16 @@ func Create(config *Config) func(db *gorm.DB) {
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) {
case map[string]interface{}:
values["@id"] = insertID
values[pkFieldName] = insertID
case *map[string]interface{}:
(*values)["@id"] = insertID
(*values)[pkFieldName] = insertID
case []map[string]interface{}, *[]map[string]interface{}:
mapValues, ok := values.([]map[string]interface{})
if !ok {
Expand All @@ -179,7 +185,7 @@ func Create(config *Config) func(db *gorm.DB) {
}
for _, mapValue := range mapValues {
if mapValue != nil {
mapValue["@id"] = insertID
mapValue[pkFieldName] = insertID
}
insertID += schema.DefaultAutoIncrementIncrement
}
Expand Down

0 comments on commit 9dd2821

Please sign in to comment.