//MODELS
type User struct {
ID int `json:"id,omitempty" gorm:"primaryKey"`
EmployeeCode string `json:"employee_code,omitempty" gorm:"unique"`
FirstName string `json:"first_name" validate:"required,max=50" `
MiddleName string `json:"middle_name,omitempty" validate:"max=50"`
LastName string `json:"last_name" validate:"required,max=50" `
MobileNo string `json:"mobile_no" validate:"required,max=10,numeric"`
Email string `json:"email" validate:"required,email"`
Password string `json:"-" `
Status string `json:"status,omitempty" `
CreatedAt time.Time `json:"created_at"`
Roles []Role `json:"roles" gorm:"many2many:user_role" `
}
type Role struct {
ID int `json:"id,omitempty" gorm:"primaryKey"`
RoleName string `json:"role_name" validate:"required,max=50" gorm:"unique"`
RoleDescription string `json:"role_description" validate:"required,max=150"`
Status string `json:"status"`
}
//FUnctionality
func (u *userEnitity) EditUser(emplyeeCode string, user models.User) (models.User, int, string) {
var tx *gorm.DB
var statusCode = 200
var errText string
var count int64
var id int
var roleId []int
count = 0
if tx = u.resource.Select("id").Model(&models.User{}).Where("employee_code = ? ", emplyeeCode).Scan(&id).Count(&count); tx.Error != nil {
return user, statusCode, errText
}
if count == 0 {
return user, 400, "User does not exist"
}
u.resource.Debug().Model(&models.User{}).Where("id = ?", id).Updates(models.User{
FirstName: user.FirstName,
MiddleName: user.MiddleName,
LastName: user.LastName,
MobileNo: user.MobileNo,
Email: user.Email,
})
if tx = u.resource.Table("user_role").Select("role_id").Where("user_id = ?", id).Scan(&roleId); tx.Error != nil {
return user, statusCode, errText
}
u.resource.Debug().Model(&models.User{}).Where("id = ?", roleId).Association("Roles").Replace(&user.Roles)
return user, statusCode, errText
}