工具
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.

90 lines
2.0 KiB

4 years ago
  1. package hasaki_{{.app_name}}
  2. import (
  3. "errors"
  4. "git.ouxuan.net/hasaki-service/hasaki-sdk/hsktime"
  5. "strconv"
  6. "xorm.io/xorm"
  7. )
  8. type Model struct {
  9. Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
  10. CreatedAt hsktime.Time `json:"created_at" xorm:"created comment('创建时间')"`
  11. UpdatedAt hsktime.Time `json:"updated_at" xorm:"updated comment('更新时间')"`
  12. DeletedAt hsktime.Time `json:"-" xorm:"deleted comment('是否删除') TIMESTAMP INDEX"`
  13. session *xorm.Session `xorm:"-"`
  14. instance interface{} `xorm:"-"`
  15. }
  16. func (m *Model) checkInstance() error {
  17. if m.instance == nil {
  18. return errors.New("instance 未实例化")
  19. }
  20. return nil
  21. }
  22. func (m *Model) SetInstance(instance interface{}) {
  23. m.instance = instance
  24. }
  25. // 增删改查
  26. func (m *Model) Save(cols ...string) (int64, error) {
  27. err := m.checkInstance()
  28. if err != nil {
  29. return 0, err
  30. }
  31. if m.Id > 0 {
  32. if len(cols) > 0 {
  33. return m.session.Cols(cols...).Update(m.instance)
  34. } else {
  35. return m.session.AllCols().Update(m.session)
  36. }
  37. } else {
  38. return m.session.InsertOne(m.instance)
  39. }
  40. }
  41. func (m *Model) Del() (int64, error) {
  42. err := m.checkInstance()
  43. if err != nil {
  44. return 0, err
  45. }
  46. return m.session.ID(m.Id).Delete(m.instance)
  47. }
  48. func (m *Model) Get() (bool, error) {
  49. err := m.checkInstance()
  50. if err != nil {
  51. return false, err
  52. }
  53. return m.session.Unscoped().Get(m.instance)
  54. }
  55. //分页 cond["page"] 第几页 cond["page_size"] 多少条
  56. func Page(cond map[string]string, s *xorm.Session) *xorm.Session {
  57. if cond["page_size"] != "" {
  58. size, _ := strconv.Atoi(cond["page_size"])
  59. page, _ := strconv.Atoi(cond["page"])
  60. if page <= 0 {
  61. page = 0
  62. } else {
  63. page = page - 1
  64. }
  65. s = s.Limit(size, page*size)
  66. }
  67. return s
  68. }
  69. func Like(col, key string, s *xorm.Session) *xorm.Session {
  70. if key != "" {
  71. s = s.Where(col+" like ?", "%"+key+"%")
  72. }
  73. return s
  74. }
  75. func JsonContains(col, key string, s *xorm.Session) *xorm.Session {
  76. if key != "" {
  77. s = s.Where(`JSON_CONTAINS(` + col + `, '` + key + `', '$')`)
  78. }
  79. return s
  80. }