zhangqian
2023-10-30 4d0b38be2e3977ec390f70de2f022fe96c4cbb61
model/user.go
@@ -5,14 +5,13 @@
   "aps_crm/pkg/mysqlx"
   "fmt"
   "gorm.io/gorm"
   "gorm.io/gorm/clause"
)
type (
   // User token里边把用户ID、父用户ID、角色都带上
   User struct {
      ID           int               `json:"id" gorm:"column:id;primary_key;AUTO_INCREMENT"`
      UUID         string            `json:"uuid" gorm:"unique;type:varchar(255);comment:用户ID"`
      UUID         string            `json:"uuid" gorm:"uniqueIndex;type:varchar(255);comment:用户ID"`
      Username     string            `json:"username" gorm:"index;type:varchar(255);comment:用户登录名"`
      UserType     constvar.UserType `json:"userType" gorm:"type:int(11);comment:用户类型 1超级管理员 2主账户 3子账户"`
      Password     string            `json:"-"  gorm:"type:varchar(255);comment:用户登录密码"`
@@ -294,13 +293,24 @@
}
func (slf *UserSearch) Upsert(record User) error {
   var db = slf.build()
   if err := db.Clauses(clause.OnConflict{
      Columns:   []clause.Column{{Name: "uuid"}},
      DoUpdates: clause.AssignmentColumns([]string{"username", "user_type", "nick_name", "sub_user_ids"}),
   }).Create(&record).Error; err != nil {
      return fmt.Errorf("first or create err: %v, record: %+v", err, record)
   var db = slf.SetId(record.UUID).build()
   old, err := slf.First()
   if err == gorm.ErrRecordNotFound {
      if err := db.Create(&record).Error; err != nil {
         return fmt.Errorf("create user err: %v, record: %+v", err, record)
      }
   } else if old.Username != record.Username ||
      old.UserType != record.UserType ||
      old.NickName != record.NickName ||
      old.SubUserIds != record.SubUserIds {
      old.Username = record.Username
      old.UserType = record.UserType
      old.NickName = record.NickName
      old.SubUserIds = record.SubUserIds
      if err := db.Updates(&record).Error; err != nil {
         return fmt.Errorf("update user err: %v, record: %+v", err, record)
      }
   }
   return nil