互动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.0 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package models
  2. import (
  3. "fmt"
  4. "github.com/xormplus/xorm"
  5. "reflect"
  6. "strings"
  7. "github.com/ouxuanserver/osmanthuswine/src/core"
  8. )
  9. func Condition(condition map[string]interface{}) *xorm.Session {
  10. session := core.GetXormAuto().NewSession()
  11. for k, v := range condition {
  12. if strings.Contains(k, " not in") {
  13. session = session.NotIn(strings.TrimRight(k, " not in"), v)
  14. } else if strings.Contains(k, " in") {
  15. session = session.In(strings.TrimRight(k, " in"), v)
  16. } else if strings.HasPrefix(strings.ToLower(k), "order by") {
  17. session = session.OrderBy(v.(string))
  18. } else if strings.HasSuffix(k, "<") || strings.HasSuffix(k, ">") ||
  19. strings.HasSuffix(k, "<=") || strings.HasSuffix(k, ">=") ||
  20. strings.HasSuffix(k, "<>") || strings.HasSuffix(k, "=") ||
  21. strings.HasSuffix(k, "!=") {
  22. session = session.Where(fmt.Sprintf("%s?", k), v)
  23. } else {
  24. session = session.Where(fmt.Sprintf("%s=?", k), v)
  25. }
  26. }
  27. return session
  28. }
  29. func Save(condition map[string]interface{}, obj interface{}, filed ...string) error {
  30. session := Condition(condition)
  31. defer session.Close()
  32. if condition != nil && Exist(Condition(condition), reflect.New(reflect.TypeOf(obj).Elem()).Interface()) {
  33. //存在则更新
  34. _, err := session.Cols(filed...).Update(obj)
  35. return err
  36. } else {
  37. //不存在则插入
  38. _, err := session.InsertOne(obj)
  39. return err
  40. }
  41. }
  42. func Exist(session *xorm.Session, obj interface{}) (result bool) {
  43. defer session.Close()
  44. result, _ = session.Exist(obj)
  45. return result
  46. }
  47. func GetTableName(bean interface{}) string {
  48. if table, ok := bean.(string); ok {
  49. return table
  50. }
  51. return core.GetXormAuto().TableName(bean)
  52. }
  53. func AliasTableName(bean interface{}, alias string) string {
  54. tn := GetTableName(bean)
  55. return fmt.Sprintf("%s as %s", tn, alias)
  56. }
  57. func GetById(bean interface{}, id int64) (bool, error) {
  58. return core.GetXormAuto().Where("is_delete=0 and id=?", id).Get(bean)
  59. }
  60. // Clone copy all the session's content and return a new session
  61. func CloneSession(session *xorm.Session) *xorm.Session {
  62. var sess = *session
  63. return &sess
  64. }