diff --git a/model.go b/model.go index 7df9b7f3..dd7189b8 100644 --- a/model.go +++ b/model.go @@ -4,6 +4,7 @@ import ( "fmt" "reflect" "regexp" + "strings" ) @@ -23,6 +24,11 @@ func (s *Orm) toModel(value interface{}) *Model { return &Model{Data: value, driver: s.driver} } +func (m *Model) PrimaryKeyIsEmpty() bool { + result := reflect.ValueOf(m.Data).Elem() + return result.FieldByName(m.PrimaryKey()).Interface().(int64) == int64(0) +} + func (m *Model) PrimaryKey() string { return "Id" } diff --git a/orm.go b/orm.go index 1c09e75a..8bda0da7 100644 --- a/orm.go +++ b/orm.go @@ -3,6 +3,7 @@ package gorm import ( "database/sql" "errors" + "strconv" ) @@ -86,8 +87,12 @@ func (s *Orm) Select(value interface{}) *Orm { } func (s *Orm) Save(value interface{}) *Orm { - s.explain(value, "Create").create(value) - // s.explain(value, "Update").update(value) + s.setModel(value) + if s.Model.PrimaryKeyIsEmpty() { + s.explain(value, "Create").create(value) + } else { + s.explain(value, "Update").update(value) + } return s }