db_base.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // @Time : 2020/10/29 8:31 下午
  2. // @Author : bingee
  3. package models
  4. import (
  5. "github.com/beego/beego/v2/client/orm"
  6. )
  7. // 是否存在
  8. func IsExistByExpr(ptrStructOrTableName interface{}, where map[string]interface{}) bool {
  9. o := orm.NewOrm()
  10. qs := o.QueryTable(ptrStructOrTableName)
  11. for expr, exprV := range where {
  12. qs = qs.Filter(expr, exprV)
  13. }
  14. return qs.Exist()
  15. }
  16. // 获取条数
  17. func GetCountByExpr(ptrStructOrTableName interface{}, where map[string]interface{}) (count int64, err error) {
  18. o := orm.NewOrm()
  19. qs := o.QueryTable(ptrStructOrTableName)
  20. for expr, exprV := range where {
  21. qs = qs.Filter(expr, exprV)
  22. }
  23. count, err = qs.Count()
  24. return
  25. }
  26. // 更新
  27. func UpdateByExpr(ptrStructOrTableName interface{}, where map[string]interface{}, updateParams orm.Params) error {
  28. o := orm.NewOrm()
  29. qs := o.QueryTable(ptrStructOrTableName)
  30. for expr, exprV := range where {
  31. qs = qs.Filter(expr, exprV)
  32. }
  33. _, err := qs.Update(updateParams)
  34. return err
  35. }
  36. // 删除
  37. func DeleteByExpr(ptrStructOrTableName interface{}, where map[string]interface{}) error {
  38. o := orm.NewOrm()
  39. qs := o.QueryTable(ptrStructOrTableName)
  40. for expr, exprV := range where {
  41. qs = qs.Filter(expr, exprV)
  42. }
  43. _, err := qs.Delete()
  44. return err
  45. }
  46. // 插入
  47. func InsertData(ptrStructOrTableName interface{}) (int64, error) {
  48. o := orm.NewOrm()
  49. id, err := o.Insert(ptrStructOrTableName)
  50. return id, err
  51. }
  52. // 获取数据
  53. func GetDataByExpr(ptrStructOrTableName interface{}, where map[string]interface{}, data interface{}, page ...int64) (err error) {
  54. o := orm.NewOrm()
  55. qs := o.QueryTable(ptrStructOrTableName)
  56. for expr, exprV := range where {
  57. qs = qs.Filter(expr, exprV)
  58. }
  59. if len(page) > 1 {
  60. qs = qs.Limit(page[1], page[0])
  61. }
  62. _, err = qs.All(data)
  63. return err
  64. }