forked from mirror/gorm
Don't sort by primary key if it doesn't exist in First/Last
This commit is contained in:
parent
0c63e57f5c
commit
d7400c2df4
12
main.go
12
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
|
||||
}
|
||||
|
||||
|
|
8
utils.go
8
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 {
|
||||
|
|
Loading…
Reference in New Issue