Added offset when scanning the result back to struct

This commit is contained in:
Hasan 2022-03-08 04:08:16 +06:00
parent b566ed7913
commit aeaca493cf
1 changed files with 23 additions and 5 deletions

20
scan.go
View File

@ -157,6 +157,8 @@ func Scan(rows *sql.Rows, db *DB, mode ScanMode) {
default: default:
var ( var (
fields = make([]*schema.Field, len(columns)) fields = make([]*schema.Field, len(columns))
selectFields []*schema.Field
selectedColumnsMap = map[string]int{}
joinFields [][2]*schema.Field joinFields [][2]*schema.Field
sch = db.Statement.Schema sch = db.Statement.Schema
reflectValue = db.Statement.ReflectValue reflectValue = db.Statement.ReflectValue
@ -194,7 +196,23 @@ func Scan(rows *sql.Rows, db *DB, mode ScanMode) {
if sch != nil { if sch != nil {
for idx, column := range columns { for idx, column := range columns {
if field := sch.LookUpField(column); field != nil && field.Readable { if field := sch.LookUpField(column); field != nil && field.Readable {
fields[idx] = field selectFields = sch.Fields
offset := 0
if index, ok := selectedColumnsMap[column]; ok {
offset = index + 1
selectFields = selectFields[offset:]
}
for fieldIndex, selectField := range selectFields {
if selectField.DBName == column {
fields[idx] = selectField
selectedColumnsMap[column] = offset + fieldIndex
if selectField.Readable {
break
}
}
}
} else if names := strings.Split(column, "__"); len(names) > 1 { } else if names := strings.Split(column, "__"); len(names) > 1 {
if rel, ok := sch.Relationships.Relations[names[0]]; ok { if rel, ok := sch.Relationships.Relations[names[0]]; ok {
if field := rel.FieldSchema.LookUpField(strings.Join(names[1:], "__")); field != nil && field.Readable { if field := rel.FieldSchema.LookUpField(strings.Join(names[1:], "__")); field != nil && field.Readable {