From 4c1a78bab7496c6db3c40ebb5d73cdd549bef35b Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 4 Dec 2015 18:41:28 +0800 Subject: [PATCH] Don't query all columns out from database after create, but only those has default value --- callback_create.go | 11 ++++++++--- callback_query.go | 4 +++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/callback_create.go b/callback_create.go index 71db4ef0..d13a71be 100644 --- a/callback_create.go +++ b/callback_create.go @@ -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) } } diff --git a/callback_query.go b/callback_query.go index 387e813d..5473f232 100644 --- a/callback_query.go +++ b/callback_query.go @@ -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{}