Skip to content

Commit a219afc

Browse files
authored
fix-struct-nested-reflection (#40)
1 parent 8e92797 commit a219afc

File tree

1 file changed

+32
-14
lines changed

1 file changed

+32
-14
lines changed

gplus/query.go

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -285,35 +285,53 @@ func (q *Query[T]) buildColumnNameMap() *T {
285285
}
286286
q.ColumnNameMap = make(map[uintptr]string)
287287
model := new(T)
288-
valueOf := reflect.ValueOf(model)
289-
typeOf := reflect.TypeOf(model)
288+
valueOf := reflect.ValueOf(model).Elem()
289+
typeOf := reflect.TypeOf(model).Elem()
290290

291-
for i := 0; i < valueOf.Elem().NumField(); i++ {
292-
field := typeOf.Elem().Field(i)
291+
for i := 0; i < valueOf.NumField(); i++ {
292+
field := typeOf.Field(i)
293293
if field.Anonymous {
294-
modelType := field.Type
295-
if modelType.Kind() == reflect.Ptr {
296-
modelType = modelType.Elem()
297-
}
298-
for j := 0; j < modelType.NumField(); j++ {
299-
pointer := valueOf.Elem().FieldByName(modelType.Field(j).Name).Addr().Pointer()
300-
name := parseColumnName(modelType.Field(j))
301-
q.ColumnNameMap[pointer] = name
294+
subFieldMap := getSubFieldColumnNameMap(valueOf, field)
295+
for key, value := range subFieldMap {
296+
q.ColumnNameMap[key] = value
302297
}
303298
} else {
304-
pointer := valueOf.Elem().Field(i).Addr().Pointer()
299+
pointer := valueOf.Field(i).Addr().Pointer()
305300
name := parseColumnName(field)
306301
q.ColumnNameMap[pointer] = name
307302
}
308303
}
309-
310304
// store to cache
311305
modelInstanceCache.Store(modelTypeStr, model)
312306
columnNameMapCache.Store(modelTypeStr, q.ColumnNameMap)
313307

314308
return model
315309
}
316310

311+
func getSubFieldColumnNameMap(valueOf reflect.Value, field reflect.StructField) map[uintptr]string {
312+
result := make(map[uintptr]string)
313+
314+
modelType := field.Type
315+
if modelType.Kind() == reflect.Ptr {
316+
modelType = modelType.Elem()
317+
}
318+
for j := 0; j < modelType.NumField(); j++ {
319+
subField := modelType.Field(j)
320+
if subField.Anonymous {
321+
nestedFields := getSubFieldColumnNameMap(valueOf, subField)
322+
for key, value := range nestedFields {
323+
result[key] = value
324+
}
325+
} else {
326+
pointer := valueOf.FieldByName(modelType.Field(j).Name).Addr().Pointer()
327+
name := parseColumnName(modelType.Field(j))
328+
result[pointer] = name
329+
}
330+
}
331+
332+
return result
333+
}
334+
317335
func parseColumnName(field reflect.StructField) string {
318336
tagSetting := schema.ParseTagSetting(field.Tag.Get("gorm"), ";")
319337
name, ok := tagSetting["COLUMN"]

0 commit comments

Comments
 (0)