2022-08-30 08:25:28

gorm杂记

1. model 随手记

type User struct { Id int64 `json:"id" gorm:"primaryKey"` Username string `json:"username"` Nickname string `json:"nickname"` Password string `json:"-"` Phone string `json:"phone"` CreateAt int64 `json:"create_at"` CreateBy string `json:"create_by"` UpdateAt int64 `json:"update_at"` UpdateBy string `json:"update_by"` } func (u *User) TableName() string { return "users" } func (u *User) Verify() error { ... } // 增加用户 func (u *User) Add() error { user, err := UserGetByUsername(u.Username) if err != nil { return errors.WithMessage(err, "failed to query user") } if user != nil { return errors.New("Username already exists") } now := time.Now().Unix() u.CreateAt = now u.UpdateAt = now return Insert(u) } // 更新用户部分字段 func (u *User) Update(selectField interface{}, selectFields ...interface{}) error { if err := u.Verify(); err != nil { return err } return DB().Model(u).Select(selectField, selectFields).Updates(u).Error } // 更新所有字段 func (u *User) UpdateAllFields() error { if err := u.Verify(); err != nil { return err } u.UpdateAt = time.Now().Unix() return DB().Model(u).Select("*").Updates(u).Error } // 删除,通过事务,删除关联信息 func (u *User) Del() error { return DB().Transaction(func(tx *gorm.DB) error { if err := tx.Where("user_id=?", u.Id).Delete(&UserGroupMember{}).Error; err != nil { return err } if err := tx.Where("id=?", u.Id).Delete(&User{}).Error; err != nil { return err } return nil }) } // 修改密码(一些跟users相关的操作) func (u *User) ChangePassword(oldpass, newpass string) error { _oldpass, err := CryptoPass(oldpass) if err != nil { return err } _newpass, err := CryptoPass(newpass) if err != nil { return err } if u.Password != _oldpass { return errors.New("Incorrect old password") } return u.UpdatePassword(_newpass, u.Username) } // 根据条件获取用户 func UserGet(where string, args ...interface{}) (*User, error) { var lst []*User err := DB().Where(where, args...).Find(&lst).Error if err != nil { return nil, err } if len(lst) == 0 { return nil, nil } lst[0].RolesLst = strings.Fields(lst[0].Roles) lst[0].Admin = lst[0].IsAdmin() return lst[0], nil } // 根据用户名获取用户 func UserGetByUsername(username string) (*User, error) { return UserGet("username=?", username) } // 根据ID获取用户 func UserGetById(id int64) (*User, error) { return UserGet("id=?", id) } // 总数量 func UserTotal(query string) (num int64, err error) { if query != "" { q := "%" + query + "%" num, err = Count(DB().Model(&User{}).Where("username like ? or nickname like ? or phone like ? or email like ?", q, q, q, q)) } else { num, err = Count(DB().Model(&User{})) } if err != nil { return num, errors.WithMessage(err, "failed to count user") } return num, nil } // 获取所有用户,翻页 func UserGets(query string, limit, offset int) ([]User, error) { session := DB().Limit(limit).Offset(offset).Order("username") if query != "" { q := "%" + query + "%" session = session.Where("username like ? or nickname like ? or phone like ? or email like ?", q, q, q, q) } var users []User err := session.Find(&users).Error if err != nil { return users, errors.WithMessage(err, "failed to query user") } for i := 0; i < len(users); i++ { users[i].RolesLst = strings.Fields(users[i].Roles) users[i].Admin = users[i].IsAdmin() } return users, nil } // 获取所有用户 func UserGetAll() ([]*User, error) { var lst []*User err := DB().Find(&lst).Error if err == nil { for i := 0; i < len(lst); i++ { lst[i].RolesLst = strings.Fields(lst[i].Roles) lst[i].Admin = lst[i].IsAdmin() } } return lst, err } // 批量根据id获取用户 func UserGetsByIds(ids []int64) ([]User, error) { if len(ids) == 0 { return []User{}, nil } var lst []User err := DB().Where("id in ?", ids).Order("username").Find(&lst).Error if err == nil { for i := 0; i < len(lst); i++ { lst[i].RolesLst = strings.Fields(lst[i].Roles) lst[i].Admin = lst[i].IsAdmin() } } return lst, err } // 获取用户组 func (u *User) UserGroups(limit int, query string) ([]UserGroup, error) { session := DB().Order("name").Limit(limit) var lst []UserGroup if u.IsAdmin() { err := session.Where("name like ?", "%"+query+"%").Find(&lst).Error return lst, err } ids, err := MyGroupIds(u.Id) if err != nil { return nil, errors.WithMessage(err, "failed to get MyGroupIds") } if len(ids) > 0 { session = session.Where("id in ? or create_by = ?", ids, u.Username) } else { session = session.Where("create_by = ?", u.Username) } err = session.Where("name like ?", "%"+query+"%").Find(&lst).Error return lst, err }

规范可参考这里:https://github.com/ccfos/nightingale/tree/main/src/pkg
追踪:https://github.com/avtion/gormTracing
好文章:https://segmentfault.com/a/1190000039097157

本文链接:https://troy.wang/post/gorm.html

-- EOF --