Don't query all columns out from database after create, but only those has default value

This commit is contained in:
Jinzhu 2015-12-04 18:41:28 +08:00
parent 84c6b46011
commit 4c1a78bab7
2 changed files with 11 additions and 4 deletions

View File

@ -33,7 +33,12 @@ func Create(scope *Scope) {
columns = append(columns, scope.Quote(field.DBName))
sqls = append(sqls, scope.AddToVars(field.Field.Interface()))
} else if field.HasDefaultValue {
scope.InstanceSet("gorm:force_reload_after_create", true)
var hasDefaultValueColumns []string
if oldHasDefaultValueColumns, ok := scope.InstanceGet("gorm:force_reload_after_create_attrs"); ok {
hasDefaultValueColumns = oldHasDefaultValueColumns.([]string)
}
hasDefaultValueColumns = append(hasDefaultValueColumns, field.DBName)
scope.InstanceSet("gorm:force_reload_after_create_attrs", hasDefaultValueColumns)
}
}
} else if relationship := field.Relationship; relationship != nil && relationship.Kind == "belongs_to" {
@ -98,8 +103,8 @@ func Create(scope *Scope) {
}
func ForceReloadAfterCreate(scope *Scope) {
if _, ok := scope.InstanceGet("gorm:force_reload_after_create"); ok {
scope.DB().New().First(scope.Value)
if columns, ok := scope.InstanceGet("gorm:force_reload_after_create_attrs"); ok {
scope.DB().New().Select(columns.([]string)).First(scope.Value)
}
}

View File

@ -71,7 +71,9 @@ func Query(scope *Scope) {
if field.Field.Kind() == reflect.Ptr {
values[index] = field.Field.Addr().Interface()
} else {
values[index] = reflect.New(reflect.PtrTo(field.Field.Type())).Interface()
reflectValue := reflect.New(reflect.PtrTo(field.Struct.Type))
reflectValue.Elem().Set(field.Field.Addr())
values[index] = reflectValue.Interface()
}
} else {
var value interface{}