query.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. rows, err := db.DB.QueryContext(db.Context, db.Statement.SQL.String(), db.Statement.Vars...)
  14. db.AddError(err)
  15. _ = rows
  16. // scan rows
  17. }
  18. func Preload(db *gorm.DB) {
  19. }
  20. func AfterQuery(db *gorm.DB) {
  21. if db.Statement.Schema != nil && db.Statement.Schema.AfterFind {
  22. callMethod := func(value interface{}) bool {
  23. if db.Statement.Schema.AfterFind {
  24. if i, ok := value.(gorm.AfterFindInterface); ok {
  25. i.AfterFind(db)
  26. return true
  27. }
  28. }
  29. return false
  30. }
  31. if ok := callMethod(db.Statement.Dest); !ok {
  32. switch db.Statement.ReflectValue.Kind() {
  33. case reflect.Slice, reflect.Array:
  34. for i := 0; i <= db.Statement.ReflectValue.Len(); i++ {
  35. callMethod(db.Statement.ReflectValue.Index(i).Interface())
  36. }
  37. case reflect.Struct:
  38. callMethod(db.Statement.ReflectValue.Interface())
  39. }
  40. }
  41. }
  42. }