Improve column->field map construction
Extract column map construction to a separate func and make it recursively collect fields from embedded structs.
This commit is contained in:
parent
eb26dcc597
commit
0b9218f1e5
@ -6,6 +6,30 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func getColumnMap(destType reflect.Type) map[string]string {
|
||||||
|
colToFieldMap := make(map[string]string)
|
||||||
|
if destType != nil && destType.Kind() == reflect.Struct {
|
||||||
|
for i := 0; i < destType.NumField(); i++ {
|
||||||
|
field := destType.Field(i)
|
||||||
|
if field.Anonymous {
|
||||||
|
embeddedStructFields := getColumnMap(field.Type)
|
||||||
|
for k, v := range embeddedStructFields {
|
||||||
|
colToFieldMap[k] = v
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fieldName := field.Name
|
||||||
|
dbColumnName := ToSnake(fieldName)
|
||||||
|
settings := parseTagSetting(destType.Field(i).Tag.Get("gorm"))
|
||||||
|
if colName, ok := settings["COLUMN"]; ok && colName != "" {
|
||||||
|
dbColumnName = colName
|
||||||
|
}
|
||||||
|
colToFieldMap[dbColumnName] = fieldName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return colToFieldMap
|
||||||
|
}
|
||||||
|
|
||||||
func Query(scope *Scope) {
|
func Query(scope *Scope) {
|
||||||
defer scope.Trace(time.Now())
|
defer scope.Trace(time.Now())
|
||||||
|
|
||||||
@ -41,18 +65,7 @@ func Query(scope *Scope) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
colToFieldMap := make(map[string]string)
|
colToFieldMap := getColumnMap(destType)
|
||||||
if destType != nil && destType.Kind() == reflect.Struct {
|
|
||||||
for i := 0; i < destType.NumField(); i++ {
|
|
||||||
fieldName := destType.Field(i).Name
|
|
||||||
dbColumnName := ToSnake(fieldName)
|
|
||||||
settings := parseTagSetting(destType.Field(i).Tag.Get("gorm"))
|
|
||||||
if colName, ok := settings["COLUMN"]; ok && colName != "" {
|
|
||||||
dbColumnName = colName
|
|
||||||
}
|
|
||||||
colToFieldMap[dbColumnName] = fieldName
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user