Order results when preload many2many relations

This commit is contained in:
Jinzhu 2016-02-14 17:21:40 +08:00
parent ea40d075fe
commit 421979cfc2
1 changed files with 7 additions and 2 deletions

View File

@ -188,7 +188,7 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface
var (
relation = field.Relationship
joinTableHandler = relation.JoinTableHandler
fieldType = field.StructField.Struct.Type.Elem()
fieldType = field.Struct.Type.Elem()
foreignKeyValue interface{}
foreignKeyType = reflect.ValueOf(&foreignKeyValue).Type()
linkHash = map[string][]reflect.Value{}
@ -206,9 +206,14 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface
}
// generate query with join table
preloadJoinDB := scope.NewDB().Table(scope.New(reflect.New(fieldType).Interface()).TableName()).Select("*")
newScope := scope.New(reflect.New(fieldType).Interface())
preloadJoinDB := scope.NewDB().Table(newScope.TableName()).Select("*")
preloadJoinDB = joinTableHandler.JoinWith(joinTableHandler, preloadJoinDB, scope.Value)
if primaryField := newScope.PrimaryField(); primaryField != nil {
preloadJoinDB = preloadJoinDB.Order(fmt.Sprintf("%v.%v %v", newScope.QuotedTableName(), newScope.Quote(primaryField.DBName), "ASC"))
}
// preload inline conditions
if len(conditions) > 0 {
preloadJoinDB = preloadJoinDB.Where(conditions[0], conditions[1:]...)