Refact First, Last to make it possible to reset table name in Plugin

This commit is contained in:
Jinzhu 2014-08-25 16:41:26 +08:00
parent 39ac95adbb
commit 3af077ac46
2 changed files with 11 additions and 14 deletions

View File

@ -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()

18
main.go
View File

@ -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 {