Fix support embedded pointer type struct, close #1450

This commit is contained in:
Jinzhu 2018-02-13 10:00:07 +08:00
parent fe3c94cd2d
commit 67c4280c57
2 changed files with 21 additions and 0 deletions

View File

@ -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")
}
}

View File

@ -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)})