add MapColumns method

This commit is contained in:
molon 2024-03-15 03:15:05 +08:00
parent e4e23d26d2
commit ef066ff4ed
3 changed files with 19 additions and 2 deletions

View File

@ -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.

View File

@ -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) {

View File

@ -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