Add ORDER BY sql expression support

This commit is contained in:
Jinzhu 2016-06-28 11:15:42 +08:00
parent 321d10b67b
commit c1c4f9f86e
4 changed files with 25 additions and 10 deletions

View File

@ -166,7 +166,10 @@ func (s *DB) Offset(offset interface{}) *DB {
} }
// Order specify order when retrieve records from database, set reorder to `true` to overwrite defined conditions // Order specify order when retrieve records from database, set reorder to `true` to overwrite defined conditions
func (s *DB) Order(value string, reorder ...bool) *DB { // db.Order("name DESC")
// db.Order("name DESC", true) // reorder
// db.Order(gorm.Expr("name = ? DESC", "first")) // sql expression
func (s *DB) Order(value interface{}, reorder ...bool) *DB {
return s.clone().search.Order(value, reorder...).db return s.clone().search.Order(value, reorder...).db
} }

View File

@ -307,6 +307,12 @@ func TestOrderAndPluck(t *testing.T) {
DB.Save(&user1).Save(&user2).Save(&user3) DB.Save(&user1).Save(&user2).Save(&user3)
scopedb := DB.Model(&User{}).Where("name like ?", "%OrderPluckUser%") scopedb := DB.Model(&User{}).Where("name like ?", "%OrderPluckUser%")
var user User
scopedb.Order(gorm.Expr("name = ? DESC", "OrderPluckUser2")).First(&user)
if user.Name != "OrderPluckUser2" {
t.Errorf("Order with sql expression")
}
var ages []int64 var ages []int64
scopedb.Order("age desc").Pluck("age", &ages) scopedb.Order("age desc").Pluck("age", &ages)
if ages[0] != 20 { if ages[0] != 20 {

View File

@ -730,7 +730,15 @@ func (scope *Scope) orderSQL() string {
var orders []string var orders []string
for _, order := range scope.Search.orders { for _, order := range scope.Search.orders {
orders = append(orders, scope.quoteIfPossible(order)) if str, ok := order.(string); ok {
orders = append(orders, scope.quoteIfPossible(str))
} else if expr, ok := order.(*expr); ok {
exp := expr.expr
for _, arg := range expr.args {
exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
}
orders = append(orders, exp)
}
} }
return " ORDER BY " + strings.Join(orders, ",") return " ORDER BY " + strings.Join(orders, ",")
} }

View File

@ -13,7 +13,7 @@ type search struct {
assignAttrs []interface{} assignAttrs []interface{}
selects map[string]interface{} selects map[string]interface{}
omits []string omits []string
orders []string orders []interface{}
preload []searchPreload preload []searchPreload
offset interface{} offset interface{}
limit interface{} limit interface{}
@ -59,14 +59,12 @@ func (s *search) Assign(attrs ...interface{}) *search {
return s return s
} }
func (s *search) Order(value string, reorder ...bool) *search { func (s *search) Order(value interface{}, reorder ...bool) *search {
if len(reorder) > 0 && reorder[0] { if len(reorder) > 0 && reorder[0] {
if value != "" { s.orders = []interface{}{}
s.orders = []string{value}
} else {
s.orders = []string{}
} }
} else if value != "" {
if value != nil {
s.orders = append(s.orders, value) s.orders = append(s.orders, value)
} }
return s return s