search.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package dto
  2. import (
  3. "ERP_storage/dto/search"
  4. "fmt"
  5. "gorm.io/gorm"
  6. "strings"
  7. )
  8. var (
  9. Source string
  10. Driver string
  11. DBName string
  12. )
  13. type GeneralDelDto struct {
  14. Id int `uri:"id" json:"id" validate:"required"`
  15. Ids []int `json:"ids"`
  16. }
  17. func (g GeneralDelDto) GetIds() []int {
  18. ids := make([]int, 0)
  19. if g.Id != 0 {
  20. ids = append(ids, g.Id)
  21. }
  22. if len(g.Ids) > 0 {
  23. for _, id := range g.Ids {
  24. if id > 0 {
  25. ids = append(ids, id)
  26. }
  27. }
  28. } else {
  29. if g.Id > 0 {
  30. ids = append(ids, g.Id)
  31. }
  32. }
  33. if len(ids) <= 0 {
  34. //方式全部删除
  35. ids = append(ids, 0)
  36. }
  37. return ids
  38. }
  39. type GeneralGetDto struct {
  40. Id int `uri:"id" json:"id" validate:"required"`
  41. }
  42. func MakeCondition(q interface{}) func(db *gorm.DB) *gorm.DB {
  43. return func(db *gorm.DB) *gorm.DB {
  44. condition := &search.GormCondition{
  45. GormPublic: search.GormPublic{},
  46. Join: make([]*search.GormJoin, 0),
  47. }
  48. search.ResolveSearchQuery(Driver, q, condition)
  49. for _, join := range condition.Join {
  50. if join == nil {
  51. continue
  52. }
  53. db = db.Joins(join.JoinOn)
  54. for k, v := range join.Where {
  55. db = db.Where(k, v...)
  56. }
  57. for k, v := range join.Or {
  58. db = db.Or(k, v...)
  59. }
  60. for _, o := range join.Order {
  61. db = db.Order(o)
  62. }
  63. }
  64. for k, v := range condition.Where {
  65. db = db.Where(k, v...)
  66. }
  67. for k, v := range condition.Or {
  68. db = db.Or(k, v...)
  69. }
  70. var orContains string
  71. for k, v := range condition.OrContains {
  72. orContains += fmt.Sprintf(" OR %v '%v'", k, v[0])
  73. }
  74. if len(orContains) > 0 {
  75. db = db.Where(strings.TrimLeft(orContains, " OR"))
  76. }
  77. for _, o := range condition.Order {
  78. db = db.Order(o)
  79. }
  80. return db
  81. }
  82. }
  83. func Paginate(pageSize, pageIndex int) func(db *gorm.DB) *gorm.DB {
  84. return func(db *gorm.DB) *gorm.DB {
  85. if pageSize == 9999 {
  86. return db
  87. }
  88. offset := (pageIndex - 1) * pageSize
  89. if offset < 0 {
  90. offset = 0
  91. }
  92. return db.Offset(offset).Limit(pageSize)
  93. }
  94. }
  95. func WithNormalState() func(db *gorm.DB) *gorm.DB {
  96. return func(db *gorm.DB) *gorm.DB {
  97. return db.Where("t__state = 1")
  98. }
  99. }