diff --git a/chainable_api.go b/chainable_api.go index 1ec9b865..a04d3d2f 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -185,6 +185,13 @@ func (db *DB) Omit(columns ...string) (tx *DB) { return } +// MapColumns specify column-to-field for customizing how database columns are assigned to struct fields during querying +func (db *DB) MapColumns(m map[string]string) (tx *DB) { + tx = db.getInstance() + tx.Statement.ColumnMapping = m + return +} + // Where add conditions // // See the [docs] for details on the various formats that where clauses can take. By default, where clauses chain with AND. diff --git a/scan.go b/scan.go index 54cd6769..4ddd591d 100644 --- a/scan.go +++ b/scan.go @@ -131,6 +131,15 @@ func Scan(rows Rows, db *DB, mode ScanMode) { onConflictDonothing = mode&ScanOnConflictDoNothing != 0 ) + if len(db.Statement.ColumnMapping) > 0 { + for i, column := range columns { + v, ok := db.Statement.ColumnMapping[column] + if ok { + columns[i] = v + } + } + } + db.RowsAffected = 0 switch dest := db.Statement.Dest.(type) { diff --git a/statement.go b/statement.go index ae79aa32..7d31088b 100644 --- a/statement.go +++ b/statement.go @@ -30,8 +30,9 @@ type Statement struct { Clauses map[string]clause.Clause BuildClauses []string Distinct bool - Selects []string // selected columns - Omits []string // omit columns + Selects []string // selected columns + Omits []string // omit columns + ColumnMapping map[string]string // map columns Joins []join Preloads map[string][]interface{} Settings sync.Map