今天我們使用gorm有某場景需要動态拼接sql語句,擷取結果title為動态修改。
事情背景:
此前我們使用beego開發使用beego自帶orm,處理此類問題可定義接收變量為([]orm.Params)例如
var maps []orm.Params
if _, err := o.Raw(sql).Values(&maps);err!=nil {
return
}
現在項目重構使用gin+gorm+redigo+iview結構
在處理此類問題時候發現gorm常用方法中并沒有接收可變結果集的方法,經過重重困難終于找到可以使用scan方法解決此類問題,代碼如下
query := factory.DB()
rows, _ := query.Raw(sql, endTime, endTime, endTime, startTime, startTime, endTime).Rows()
cols, _ := rows.Columns()
for rows.Next() {
// Create a slice of interface{}'s to represent each column,
// and a second slice to contain pointers to each item in the columns slice.
columns := make([]interface{}, len(cols))
columnPointers := make([]interface{}, len(cols))
for i, _ := range columns {
columnPointers[i] = &columns[i]
}
// Scan the result into the column pointers...
if err := rows.Scan(columnPointers...); err != nil {
return nil, err
}
// Create our map, and retrieve the value for each column from the pointers slice,
// storing it in the map with the name of the column as the key.
m := make(map[string]interface{})
for i, colName := range cols {
val := columnPointers[i].(*interface{})
if colName == "time" {
interfaceData := *val
ba := []byte{}
for _, b := range interfaceData.([]uint8) {
ba = append(ba, byte(b))
}
m[colName] = string(ba)
} else {
m[colName] = *val
}
}
// Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
chartList = append(chartList, m)
}
此解決方法借鑒至:https://kylewbanks.com/blog/query-result-to-map-in-golang