Add method PrimaryKeyIsEmpty for model

This commit is contained in:
Jinzhu 2013-10-26 20:53:21 +08:00
parent cef81cba11
commit 2f4945dc35
2 changed files with 13 additions and 2 deletions

View File

@ -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"
}

7
orm.go
View File

@ -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.setModel(value)
if s.Model.PrimaryKeyIsEmpty() {
s.explain(value, "Create").create(value)
// s.explain(value, "Update").update(value)
} else {
s.explain(value, "Update").update(value)
}
return s
}