From d7400c2df4ba6eafb8114bc369fd28eacf443dc5 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 29 Jul 2014 18:29:03 +0800 Subject: [PATCH] Don't sort by primary key if it doesn't exist in First/Last --- main.go | 12 ++++++++++-- utils.go | 8 +++++++- 2 files changed, 17 insertions(+), 3 deletions(-) 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 {