interface.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. ******************************************************************************
  3. * @file interface.go
  4. * @author MakerYang
  5. ******************************************************************************
  6. */
  7. package Database
  8. import (
  9. "github.com/jinzhu/gorm"
  10. "time"
  11. )
  12. type Base struct {
  13. TableName string
  14. }
  15. func New(table string) *Base {
  16. return &Base{
  17. TableName: table,
  18. }
  19. }
  20. func (base *Base) CreateData(data interface{}) error {
  21. err := Get.Table(base.TableName).Create(data).Error
  22. return err
  23. }
  24. func (base *Base) UpdateData(query interface{}, data map[string]interface{}) error {
  25. data["update_at"] = time.Now().Unix()
  26. err := Get.Table(base.TableName).Where(query).Updates(data).Error
  27. return err
  28. }
  29. func (base *Base) ExprData(query interface{}, field string, operation string, data int) error {
  30. err := Get.Table(base.TableName).Where(query).Update(field, gorm.Expr(field+" "+operation+" ?", data)).Error
  31. return err
  32. }
  33. func (base *Base) GetData(dataStruct interface{}, query interface{}, order string) error {
  34. err := Get.Table(base.TableName).Where(query).Order(order).First(dataStruct).Error
  35. return err
  36. }
  37. func (base *Base) ListData(dataStruct interface{}, query interface{}, order string, limit int) error {
  38. err := Get.Table(base.TableName).Where(query).Order(order).Limit(limit).Find(dataStruct).Error
  39. return err
  40. }
  41. func (base *Base) PageData(dataStruct interface{}, query interface{}, order string, limit int, page int) error {
  42. err := Get.Table(base.TableName).Where(query).Order(order).Limit(limit).Offset(page * limit).Find(dataStruct).Error
  43. return err
  44. }
  45. func (base *Base) CountData(query interface{}) (int, error) {
  46. count := 0
  47. err := Get.Table(base.TableName).Where(query).Count(&count).Error
  48. return count, err
  49. }
  50. func (base *Base) DeleteData(dataStruct interface{}, query interface{}) error {
  51. err := Get.Table(base.TableName).Where(query).Delete(dataStruct).Error
  52. return err
  53. }