unity.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package unity
  2. import (
  3. "errors"
  4. "lot_interlligentControl/global"
  5. )
  6. type PageParams struct {
  7. Page int `json:"page" form:"page"`
  8. Size int `json:"size" form:"size"`
  9. Desc string `json:"desc" form:"desc"`
  10. }
  11. // Paginate 使用给定的DB连接执行分页查询
  12. func Paginate[T any](params PageParams, model T) (result []T, total int64, err error) {
  13. var count int64
  14. if err = global.DBLink.Model(model).Count(&count).Error; err != nil {
  15. return nil, 0, err
  16. }
  17. // 计算偏移量并设置分页大小
  18. offset := (params.Page - 1) * params.Size
  19. // 执行实际分页查询
  20. if err = global.DBLink.Offset(offset).Limit(params.Size).Order(params.Desc).Find(&result).Error; err != nil {
  21. return nil, 0, err
  22. }
  23. return result, count, nil
  24. }
  25. // PaginateByID 根据ID进行分页查询
  26. func PaginateByID[T any](id int, params PageParams, model T) (result []T, total int64, err error) {
  27. var count int64
  28. if err = global.DBLink.Model(model).Where("create_by = ?", id).Count(&count).Error; err != nil {
  29. return nil, 0, err
  30. }
  31. // 计算偏移量并设置分页大小
  32. offset := (params.Page - 1) * params.Size
  33. // 执行实际分页查询
  34. if err = global.DBLink.Where("create_by = ?", id).Offset(offset).Limit(params.Size).Order(params.Desc).Find(&result).Error; err != nil {
  35. return nil, 0, err
  36. }
  37. return result, count, nil
  38. }
  39. // GetById 根据id查询
  40. func GetById[T any](id int, model T) (T, error) {
  41. tx := global.DBLink.Where("id = ?", id).First(&model)
  42. if tx.Error != nil {
  43. return model, errors.New("查询失败")
  44. } else {
  45. return model, nil
  46. }
  47. }
  48. // DeleteById 根据id删除
  49. func DeleteById[T any](id int, model T) (T, error) {
  50. tx := global.DBLink.Where("id = ?", id).Delete(&model)
  51. if tx.Error != nil {
  52. return model, errors.New("查询失败")
  53. } else {
  54. return model, nil
  55. }
  56. }