user.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package bizhi
  2. import (
  3. models2 "duoduo/apis/bizhi/models"
  4. orm "duoduo/database"
  5. "pmo/pkg/tools"
  6. )
  7. type User struct {
  8. ID int64 `gorm:"column:id;type:bigint(20);primary_key;AUTO_INCREMENT" json:"id"` // 主键
  9. Phone string `gorm:"column:phone;type:varchar(24)" json:"phone"` // 手机号
  10. OpenID1 string `gorm:"column:open_id_1;type:varchar(255)" json:"openId1"` // 上级open_id
  11. NickName string `gorm:"column:nick_name;type:varchar(255)" json:"nickName"` // 微信用户名
  12. AvatarUrl string `gorm:"column:avatar_url;type:varchar(255)" json:"avatarUrl"` // 头像url
  13. Admin int `gorm:"column:admin;type:int(11)" json:"admin"` // 1-管理员
  14. OpenID string `gorm:"column:open_id;type:varchar(255)" json:"openId"` // open_id
  15. CreateTime string `gorm:"column:create_time;type:datetime" json:"createTime"` // 创建时间
  16. UpdateTime string `gorm:"column:update_time;type:datetime" json:"updateTime"` // 更新时间
  17. Score int `gorm:"column:score;type:int(11)" json:"score"` // 积分
  18. }
  19. func (m *User) TableName() string {
  20. return "user"
  21. }
  22. func (u *User) GetNum() int {
  23. var count int
  24. tableCount := orm.BzMysql.Table(u.TableName()).Where("open_id = ? ", u.OpenID)
  25. tableCount.Count(&count)
  26. return count
  27. }
  28. func (u *User) Create() (User, error) {
  29. var doc User
  30. result := orm.Eloquent.Table(u.TableName()).Create(&u)
  31. if result.Error != nil {
  32. err := result.Error
  33. return doc, err
  34. }
  35. doc = *u
  36. return doc, nil
  37. }
  38. func (u *User) GetScore() (User, error) {
  39. var doc User
  40. if err := orm.BzMysql.Table(u.TableName()).Where("open_id = ?", u.OpenID).Select("score").First(&doc).Error; err != nil {
  41. return doc, err
  42. }
  43. return doc, nil
  44. }
  45. func (u *User) SubScore(req models2.SubUserScoreRequest) error {
  46. var score ScoreLog
  47. var err error
  48. tx := orm.BzMysql.Begin()
  49. defer func() {
  50. if err != nil {
  51. tx.Rollback()
  52. } else {
  53. tx.Commit()
  54. }
  55. }()
  56. score.Score = req.Score
  57. score.OpenID = req.OpenId
  58. score.CreateTime = tools.GetCurrentTimeStr()
  59. scoreStr := tools.IntToString(req.Score)
  60. if err := tx.Table(u.TableName()).Model(&u).Where("open_id = ? ", u.OpenID).Updates(
  61. map[string]interface{}{
  62. "score": "score + " + scoreStr}).Error; err != nil {
  63. return err
  64. }
  65. if err := tx.Table(score.TableName()).Create(&score).Error; err != nil {
  66. return err
  67. }
  68. return nil
  69. }