Add getPrimaryKey: analize the tag string in the struct fields and find the one marked as primaryKey

This commit is contained in:
Paolo Galeone 2014-04-02 11:00:07 +02:00
parent 5574d47f1f
commit e16601cdc0

View File

@ -10,6 +10,7 @@ import (
"strconv"
"strings"
"time"
"go/ast"
)
func (scope *Scope) primaryCondiation(value interface{}) string {
@ -472,3 +473,27 @@ func (scope *Scope) autoMigrate() *Scope {
}
return scope
}
func (scope *Scope) getPrimaryKey() string {
indirectValue := reflect.Indirect(reflect.ValueOf(scope.Value))
if !indirectValue.IsValid() {
return "id"
}
scopeTyp := indirectValue.Type()
for i := 0; i < scopeTyp.NumField(); i++ {
fieldStruct := scopeTyp.Field(i)
if !ast.IsExported(fieldStruct.Name) {
continue
}
// if primaryKey tag found, return column name
if fieldStruct.Tag.Get("primaryKey") != "" {
return toSnake(fieldStruct.Name)
}
}
//If primaryKey tag not found, fallback to id
return "id"
}