diff --git a/callback_query.go b/callback_query.go index 439e3f96..c2fd56b0 100644 --- a/callback_query.go +++ b/callback_query.go @@ -1,6 +1,7 @@ package gorm import ( + "fmt" "reflect" "strings" "time" @@ -21,6 +22,12 @@ func Query(scope *Scope) { dest = reflect.Indirect(reflect.ValueOf(value)) } + if orderBy, ok := scope.InstanceGet("gorm:order_by_primary_key"); ok { + if primaryKey := scope.PrimaryKey(); primaryKey != "" { + scope.Search = scope.Search.clone().order(fmt.Sprintf("%v.%v %v", scope.TableName(), primaryKey, orderBy)) + } + } + if dest.Kind() == reflect.Slice { isSlice = true destType = dest.Type().Elem() diff --git a/main.go b/main.go index 514c5fa8..f1eaff3e 100644 --- a/main.go +++ b/main.go @@ -153,23 +153,13 @@ func (s *DB) Assign(attrs ...interface{}) *DB { } func (s *DB) First(out interface{}, where ...interface{}) *DB { - scope := s.clone().NewScope(out) - 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 s.clone().Limit(1).NewScope(out).InstanceSet("gorm:order_by_primary_key", "ASC"). + inlineCondition(where...).callCallbacks(s.parent.callback.queries).db } func (s *DB) Last(out interface{}, where ...interface{}) *DB { - scope := s.clone().NewScope(out) - 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 s.clone().Limit(1).NewScope(out).InstanceSet("gorm:order_by_primary_key", "DESC"). + inlineCondition(where...).callCallbacks(s.parent.callback.queries).db } func (s *DB) Find(out interface{}, where ...interface{}) *DB {