log.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package model
  2. import (
  3. "github.com/jaryhe/gopkgs/logger"
  4. "github.com/jinzhu/gorm"
  5. "go.uber.org/zap"
  6. "time"
  7. )
  8. type TLog struct {
  9. ID int64 `gorm:"column:id" json:"id"`
  10. Module string `gorm:"column:module" json:"module"`
  11. Action string `gorm:"column:action" json:"action"`
  12. Origin string `gorm:"column:origin" json:"origin"`
  13. Target string `gorm:"column:target" json:"target"`
  14. Username string `gorm:"column:username" json:"username"`
  15. Uid int64 `gorm:"column:uid" json:"uid"`
  16. CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
  17. }
  18. func (p *TLog) TableName() string {
  19. return "t_log"
  20. }
  21. func (p *TLog) Insert(db *gorm.DB) error {
  22. err := db.Create(p).Error
  23. if err != nil {
  24. logger.Error("mysql",
  25. zap.String("sql", "insert into "+p.TableName()),
  26. zap.String("error", err.Error()))
  27. }
  28. return err
  29. }
  30. func (p *TLog) Count(db *gorm.DB, where map[string]interface{}, or map[string]interface{}) (int64, error) {
  31. cond, val, err := whereBuildAndOr(where, or)
  32. if err != nil {
  33. if err != nil {
  34. logger.Error("mysql",
  35. zap.String("sql", "select count from "+p.TableName()),
  36. zap.String("error", err.Error()))
  37. }
  38. return 0, err
  39. }
  40. ret := int64(0)
  41. err = db.Table(p.TableName()).Where(cond, val...).Count(&ret).Error
  42. return ret, err
  43. }
  44. func (p *TLog) List(db *gorm.DB, where map[string]interface{}, or map[string]interface{}, limit, offset int64) (list []TLog, err error) {
  45. cond, val, err := whereBuildAndOr(where, or)
  46. if err != nil {
  47. return list, err
  48. }
  49. result := db.Table(p.TableName()).Where(cond, val...).Limit(limit).Offset(offset).Find(&list)
  50. if result.Error != nil {
  51. logger.Error("mysql",
  52. zap.String("sql", "select * from "+p.TableName()),
  53. zap.String("error", result.Error.Error()))
  54. }
  55. return list, result.Error
  56. }