Don't sort by primary key if it doesn't exist in First/Last

This commit is contained in:
Jinzhu 2014-07-29 18:29:03 +08:00
parent 0c63e57f5c
commit d7400c2df4
2 changed files with 17 additions and 3 deletions

12
main.go
View File

@ -135,13 +135,21 @@ func (s *DB) Assign(attrs ...interface{}) *DB {
func (s *DB) First(out interface{}, where ...interface{}) *DB { func (s *DB) First(out interface{}, where ...interface{}) *DB {
scope := s.clone().NewScope(out) 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 return scope.inlineCondition(where...).callCallbacks(s.parent.callback.queries).db
} }
func (s *DB) Last(out interface{}, where ...interface{}) *DB { func (s *DB) Last(out interface{}, where ...interface{}) *DB {
scope := s.clone().NewScope(out) 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 return scope.inlineCondition(where...).callCallbacks(s.parent.callback.queries).db
} }

View File

@ -99,6 +99,7 @@ func GetPrimaryKey(value interface{}) string {
} }
if indirectValue.IsValid() { if indirectValue.IsValid() {
hasId := false
scopeTyp := indirectValue.Type() scopeTyp := indirectValue.Type()
for i := 0; i < scopeTyp.NumField(); i++ { for i := 0; i < scopeTyp.NumField(); i++ {
fieldStruct := scopeTyp.Field(i) fieldStruct := scopeTyp.Field(i)
@ -109,11 +110,16 @@ func GetPrimaryKey(value interface{}) string {
settings := parseTagSetting(fieldStruct.Tag.Get("gorm")) settings := parseTagSetting(fieldStruct.Tag.Get("gorm"))
if _, ok := settings["PRIMARY_KEY"]; ok { if _, ok := settings["PRIMARY_KEY"]; ok {
return fieldStruct.Name return fieldStruct.Name
} else if fieldStruct.Name == "Id" {
hasId = true
} }
} }
if hasId {
return "Id"
}
} }
return "Id" return ""
} }
func parseTagSetting(str string) map[string]string { func parseTagSetting(str string) map[string]string {