@@ -276,39 +276,54 @@ func (q *Query[T]) buildOrder(orderType string, columns ...string) {
276
276
277
277
func (q * Query [T ]) buildColumnNameMap () * T {
278
278
// first try to load from cache
279
- modelType := reflect .TypeOf ((* T )(nil )).Elem ().String ()
280
- if model , ok := modelInstanceCache .Load (modelType ); ok {
281
- if cachedColumnNameMap , ok := columnNameMapCache .Load (modelType ); ok {
279
+ modelTypeStr := reflect .TypeOf ((* T )(nil )).Elem ().String ()
280
+ if model , ok := modelInstanceCache .Load (modelTypeStr ); ok {
281
+ if cachedColumnNameMap , ok := columnNameMapCache .Load (modelTypeStr ); ok {
282
282
q .ColumnNameMap = cachedColumnNameMap .(map [uintptr ]string )
283
283
return model .(* T )
284
284
}
285
285
}
286
-
287
286
q .ColumnNameMap = make (map [uintptr ]string )
288
287
model := new (T )
289
288
valueOf := reflect .ValueOf (model )
290
289
typeOf := reflect .TypeOf (model )
290
+
291
291
for i := 0 ; i < valueOf .Elem ().NumField (); i ++ {
292
- pointer := valueOf .Elem ().Field (i ).Addr ().Pointer ()
293
292
field := typeOf .Elem ().Field (i )
294
- tagSetting := schema .ParseTagSetting (field .Tag .Get ("gorm" ), ";" )
295
- name , ok := tagSetting ["COLUMN" ]
296
- if ok {
297
- q .ColumnNameMap [pointer ] = name
293
+ 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
302
+ }
298
303
} else {
299
- namingStrategy := schema. NamingStrategy {}
300
- name = namingStrategy . ColumnName ( "" , field . Name )
304
+ pointer := valueOf . Elem (). Field ( i ). Addr (). Pointer ()
305
+ name := parseColumnName ( field )
301
306
q .ColumnNameMap [pointer ] = name
302
307
}
303
308
}
304
309
305
310
// store to cache
306
- modelInstanceCache .Store (modelType , model )
307
- columnNameMapCache .Store (modelType , q .ColumnNameMap )
311
+ modelInstanceCache .Store (modelTypeStr , model )
312
+ columnNameMapCache .Store (modelTypeStr , q .ColumnNameMap )
308
313
309
314
return model
310
315
}
311
316
317
+ func parseColumnName (field reflect.StructField ) string {
318
+ tagSetting := schema .ParseTagSetting (field .Tag .Get ("gorm" ), ";" )
319
+ name , ok := tagSetting ["COLUMN" ]
320
+ if ok {
321
+ return name
322
+ }
323
+ namingStrategy := schema.NamingStrategy {}
324
+ return namingStrategy .ColumnName ("" , field .Name )
325
+ }
326
+
312
327
func (q * Query [T ]) getColumnName (v any ) string {
313
328
var columnName string
314
329
valueOf := reflect .ValueOf (v )
0 commit comments