【英文】Gorm将自定义SQL语句查询结果映射为时间类型时报错

Preface

When mapping the query result of custom SQL statement to a time type, Gorm throws an error: unsupported Scan, storing driver.Value type []uint8 into type *time.Time.

Solution

  • Map it to a string first and then manually convert it to a time type.
1
2
3
4
5
6
7
var resultString string
var resultTime time.Time

db.Raw("SELECT created_at FROM table WHERE id = 1").Scan(&resultString)

res, err := time.Parse("2006-01-02 15:04:05", resultString)
resultTime = res

Done

References

CSDN-RenLeiGuanCha