From 67c4280c5721f23bdc13c74733bad922637c5ec1 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 13 Feb 2018 10:00:07 +0800 Subject: [PATCH] Fix support embedded pointer type struct, close #1450 --- embedded_struct_test.go | 18 ++++++++++++++++++ scope.go | 3 +++ 2 files changed, 21 insertions(+) diff --git a/embedded_struct_test.go b/embedded_struct_test.go index 91dd0563..5f8ece57 100644 --- a/embedded_struct_test.go +++ b/embedded_struct_test.go @@ -71,3 +71,21 @@ func TestSaveAndQueryEmbeddedStruct(t *testing.T) { } } } + +func TestEmbeddedPointerTypeStruct(t *testing.T) { + type HNPost struct { + *BasePost + Upvotes int32 + } + + DB.Create(&HNPost{BasePost: &BasePost{Title: "embedded_pointer_type"}}) + + var hnPost HNPost + if err := DB.First(&hnPost, "title = ?", "embedded_pointer_type").Error; err != nil { + t.Errorf("No error should happen when find embedded pointer type, but got %v", err) + } + + if hnPost.Title != "embedded_pointer_type" { + t.Errorf("Should find correct value for embedded pointer type") + } +} diff --git a/scope.go b/scope.go index cdb772ca..14baf631 100644 --- a/scope.go +++ b/scope.go @@ -115,6 +115,9 @@ func (scope *Scope) Fields() []*Field { if isStruct { fieldValue := indirectScopeValue for _, name := range structField.Names { + if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() { + fieldValue.Set(reflect.New(fieldValue.Type().Elem())) + } fieldValue = reflect.Indirect(fieldValue).FieldByName(name) } fields = append(fields, &Field{StructField: structField, Field: fieldValue, IsBlank: isBlank(fieldValue)})