12345678910111213141516171819 |
- package database
- import (
- "gorm.io/gorm"
- "reflect"
- )
- type callback struct{}
- // 处理gorm v2.0 find 为空返回nil的问题
- func (c callback) ParserError(db *gorm.DB) {
- if db.Error == nil && db.RowsAffected == 0 && (db.Statement.ReflectValue.Kind() == reflect.Slice || db.Statement.ReflectValue.Kind() == reflect.Struct) {
- db.Error = gorm.ErrRecordNotFound
- }
- }
- func RegisterCallback(db *gorm.DB) {
- _ = db.Callback().Query().After("gorm:query").Register("error_parser", callback{}.ParserError)
- }
|