function.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. #*****************************************************************************
  3. # @file function.go
  4. # @author MakerYang(https://www.makeryang.com)
  5. # @statement 免费课程配套开源项目,任何形式收费均为盗版
  6. #*****************************************************************************
  7. */
  8. package Database
  9. import (
  10. "github.com/jinzhu/gorm"
  11. "time"
  12. )
  13. // Base 声明数据库基础数据结构体
  14. type Base struct {
  15. TableName string
  16. }
  17. // New 实例化数据表
  18. func New(table string) *Base {
  19. return &Base{
  20. TableName: table,
  21. }
  22. }
  23. // CreateData 创建数据
  24. func (base *Base) CreateData(data interface{}) error {
  25. err := Get.Table(base.TableName).Create(data).Error
  26. return err
  27. }
  28. // UpdateData 更新数据
  29. func (base *Base) UpdateData(query interface{}, data map[string]interface{}) error {
  30. data["update_at"] = time.Now().Unix()
  31. err := Get.Table(base.TableName).Where(query).Updates(data).Error
  32. return err
  33. }
  34. // ExprData 更新数值类字段值
  35. func (base *Base) ExprData(query interface{}, field string, operation string, data int) error {
  36. err := Get.Table(base.TableName).Where(query).Update(field, gorm.Expr(field+" "+operation+" ?", data)).Error
  37. return err
  38. }
  39. // GetData 读取一条数据
  40. func (base *Base) GetData(dataStruct interface{}, query interface{}, order string) error {
  41. err := Get.Table(base.TableName).Where(query).Order(order).First(dataStruct).Error
  42. return err
  43. }
  44. // ListData 读取多条数据
  45. func (base *Base) ListData(dataStruct interface{}, query interface{}, order string, limit int) error {
  46. err := Get.Table(base.TableName).Where(query).Order(order).Limit(limit).Find(dataStruct).Error
  47. return err
  48. }
  49. // PageData 读取分页数据
  50. func (base *Base) PageData(dataStruct interface{}, query interface{}, order string, limit int, page int) error {
  51. err := Get.Table(base.TableName).Where(query).Order(order).Limit(limit).Offset(page * limit).Find(dataStruct).Error
  52. return err
  53. }
  54. // CountData 获取数据总数
  55. func (base *Base) CountData(query interface{}) (int, error) {
  56. count := 0
  57. err := Get.Table(base.TableName).Where(query).Count(&count).Error
  58. return count, err
  59. }
  60. // DeleteData 删除数据
  61. func (base *Base) DeleteData(dataStruct interface{}, query interface{}) error {
  62. err := Get.Table(base.TableName).Where(query).Delete(dataStruct).Error
  63. return err
  64. }