diff --git a/main.go b/main.go index bf3e65f8..1ef9c13c 100644 --- a/main.go +++ b/main.go @@ -135,13 +135,21 @@ func (s *DB) Assign(attrs ...interface{}) *DB { func (s *DB) First(out interface{}, where ...interface{}) *DB { scope := s.clone().NewScope(out) - scope.Search = scope.Search.clone().order(scope.TableName() + "." + scope.PrimaryKey()).limit(1) + if primaryKey := scope.PrimaryKey(); primaryKey != "" { + scope.Search = scope.Search.clone().order(scope.TableName() + "." + primaryKey).limit(1) + } else { + scope.Search = scope.Search.clone().limit(1) + } return scope.inlineCondition(where...).callCallbacks(s.parent.callback.queries).db } func (s *DB) Last(out interface{}, where ...interface{}) *DB { scope := s.clone().NewScope(out) - scope.Search = scope.Search.clone().order(scope.TableName() + "." + scope.PrimaryKey() + " DESC").limit(1) + if primaryKey := scope.PrimaryKey(); primaryKey != "" { + scope.Search = scope.Search.clone().order(scope.TableName() + "." + primaryKey + " DESC").limit(1) + } else { + scope.Search = scope.Search.clone().limit(1) + } return scope.inlineCondition(where...).callCallbacks(s.parent.callback.queries).db } diff --git a/utils.go b/utils.go index 04f02a31..ed10e854 100644 --- a/utils.go +++ b/utils.go @@ -99,6 +99,7 @@ func GetPrimaryKey(value interface{}) string { } if indirectValue.IsValid() { + hasId := false scopeTyp := indirectValue.Type() for i := 0; i < scopeTyp.NumField(); i++ { fieldStruct := scopeTyp.Field(i) @@ -109,11 +110,16 @@ func GetPrimaryKey(value interface{}) string { settings := parseTagSetting(fieldStruct.Tag.Get("gorm")) if _, ok := settings["PRIMARY_KEY"]; ok { return fieldStruct.Name + } else if fieldStruct.Name == "Id" { + hasId = true } } + if hasId { + return "Id" + } } - return "Id" + return "" } func parseTagSetting(str string) map[string]string {