search.go 1.9 KB

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