timestamp.go 844 B

1234567891011121314151617181920212223242526272829303132333435
  1. package orm
  2. import (
  3. . "github.com/jinzhu/gorm"
  4. )
  5. func init() {
  6. DefaultCallback.Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback)
  7. DefaultCallback.Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallback)
  8. }
  9. // updateTimeStampForCreateCallback will set `ctime`, `mtime` when creating
  10. func updateTimeStampForCreateCallback(scope *Scope) {
  11. if !scope.HasError() {
  12. now := NowFunc()
  13. if createdAtField, ok := scope.FieldByName("ctime"); ok {
  14. if createdAtField.IsBlank {
  15. createdAtField.Set(now)
  16. }
  17. }
  18. if updatedAtField, ok := scope.FieldByName("mtime"); ok {
  19. if updatedAtField.IsBlank {
  20. updatedAtField.Set(now)
  21. }
  22. }
  23. }
  24. }
  25. func updateTimeStampForUpdateCallback(scope *Scope) {
  26. if _, ok := scope.Get("gorm:update_column"); !ok {
  27. scope.SetColumn("mtime", NowFunc())
  28. }
  29. }