From 9c2c0d24140c4018af950c732ece69dd3cf2a870 Mon Sep 17 00:00:00 2001 From: Jinlong Chen Date: Tue, 2 May 2023 09:34:28 +0800 Subject: [PATCH] feat: add handling for the interface field, when an Interface field is an object that has already been instantiated, use the type of the instantiated object itself instead of interface{}. --- schema/field.go | 11 +++++++++++ schema/schema.go | 5 ++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/schema/field.go b/schema/field.go index b5103d53..8292c965 100644 --- a/schema/field.go +++ b/schema/field.go @@ -12,6 +12,7 @@ import ( "time" "github.com/jinzhu/now" + "gorm.io/gorm/clause" "gorm.io/gorm/utils" ) @@ -122,6 +123,16 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field { AutoIncrementIncrement: 1, } + if field.IndirectFieldType.Kind() == reflect.Interface { + f := schema.ModelValue.FieldByName(fieldStruct.Name) + if f.IsValid() { + e := f.Elem() + if e.IsValid() { + field.IndirectFieldType = e.Type() + } + } + } + for field.IndirectFieldType.Kind() == reflect.Ptr { field.IndirectFieldType = field.IndirectFieldType.Elem() } diff --git a/schema/schema.go b/schema/schema.go index e13a5ed1..a9c53b70 100644 --- a/schema/schema.go +++ b/schema/schema.go @@ -18,6 +18,7 @@ var ErrUnsupportedDataType = errors.New("unsupported data type") type Schema struct { Name string + ModelValue reflect.Value ModelType reflect.Type Table string PrioritizedPrimaryField *Field @@ -113,6 +114,8 @@ func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Nam if value.Kind() == reflect.Ptr && value.IsNil() { value = reflect.New(value.Type().Elem()) } + + modelValue := reflect.Indirect(value) modelType := reflect.Indirect(value).Type() if modelType.Kind() == reflect.Interface { @@ -147,7 +150,6 @@ func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Nam return s, s.err } - modelValue := reflect.New(modelType) tableName := namer.TableName(modelType.Name()) if tabler, ok := modelValue.Interface().(Tabler); ok { tableName = tabler.TableName() @@ -164,6 +166,7 @@ func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Nam schema := &Schema{ Name: modelType.Name(), + ModelValue: modelValue, ModelType: modelType, Table: tableName, FieldsByName: map[string]*Field{},