callback.go 507 B

12345678910111213141516171819
  1. package database
  2. import (
  3. "gorm.io/gorm"
  4. "reflect"
  5. )
  6. type callback struct{}
  7. // 处理gorm v2.0 find 为空返回nil的问题
  8. func (c callback) ParserError(db *gorm.DB) {
  9. if db.Error == nil && db.RowsAffected == 0 && (db.Statement.ReflectValue.Kind() == reflect.Slice || db.Statement.ReflectValue.Kind() == reflect.Struct) {
  10. db.Error = gorm.ErrRecordNotFound
  11. }
  12. }
  13. func RegisterCallback(db *gorm.DB) {
  14. _ = db.Callback().Query().After("gorm:query").Register("error_parser", callback{}.ParserError)
  15. }