query.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package callbacks
  2. import (
  3. "reflect"
  4. "github.com/jinzhu/gorm"
  5. "github.com/jinzhu/gorm/clause"
  6. )
  7. func Query(db *gorm.DB) {
  8. if db.Statement.SQL.String() == "" {
  9. db.Statement.AddClauseIfNotExists(clause.Select{})
  10. db.Statement.AddClauseIfNotExists(clause.From{})
  11. db.Statement.Build("SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "LIMIT", "FOR")
  12. }
  13. _, err := db.DB.QueryContext(db.Context, db.Statement.SQL.String(), db.Statement.Vars...)
  14. db.AddError(err)
  15. }
  16. func Preload(db *gorm.DB) {
  17. }
  18. func AfterQuery(db *gorm.DB) {
  19. if db.Statement.Schema != nil && db.Statement.Schema.AfterFind {
  20. callMethod := func(value interface{}) bool {
  21. if db.Statement.Schema.AfterFind {
  22. if i, ok := value.(gorm.AfterFindInterface); ok {
  23. i.AfterFind(db)
  24. return true
  25. }
  26. }
  27. return false
  28. }
  29. if ok := callMethod(db.Statement.Dest); !ok {
  30. switch db.Statement.ReflectValue.Kind() {
  31. case reflect.Slice, reflect.Array:
  32. for i := 0; i <= db.Statement.ReflectValue.Len(); i++ {
  33. callMethod(db.Statement.ReflectValue.Index(i).Interface())
  34. }
  35. case reflect.Struct:
  36. callMethod(db.Statement.ReflectValue.Interface())
  37. }
  38. }
  39. }
  40. }