|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- package db
-
- import (
- "applet/app/db/model"
- "applet/app/md"
- "applet/app/utils/cache"
- "applet/app/utils/logx"
- )
-
- func ProvinceGetAll() (*[]model.Province, error) {
- var provinceList []model.Province
- if err := Db.Cols("id,name").Find(&provinceList); err != nil {
- return nil, logx.Error(err)
- }
- return &provinceList, nil
- }
-
- // 获取一条记录
- func ProvinceGetOne(key string) (*model.Province, error) {
- var province model.Province
-
- if has, err := Db.Where("`id`=?", key).Get(&province); err != nil || has == false {
- if has == false {
- return &province, nil
- }
- return nil, logx.Error(err)
- }
- return &province, nil
- }
-
- func ProvinceGetOneByName(name string) (*model.Province, error) {
- var province model.Province
-
- if has, err := Db.Where("name LIKE ?", "%"+name+"%").Get(&province); err != nil || has == false {
- if has == false {
- return &province, nil
- }
- return nil, logx.Error(err)
- }
- return &province, nil
- }
-
- //单条记录获取DB
- func ProvinceGetWithDb(HKey string) string {
- cacheKey := md.OfficialProvinceCacheKey
- get, err := cache.HGetString(cacheKey, HKey)
- if err != nil || get == "" {
- province, err := ProvinceGetOne(HKey)
- if err != nil || province == nil {
- _ = logx.Error(err)
- return ""
- }
-
- // key是否存在
- cacheKeyExist := false
- if cache.Exists(cacheKey) {
- cacheKeyExist = true
- }
-
- // 设置缓存
- _, err = cache.HSet(cacheKey, HKey, province.Name)
- if err != nil {
- _ = logx.Error(err)
- return ""
- }
- if !cacheKeyExist { // 如果是首次设置 设置过期时间
- _, err := cache.Expire(cacheKey, md.CfgCacheTime)
- if err != nil {
- _ = logx.Error(err)
- return ""
- }
- }
- return province.Name
- }
- return get
- }
-
- func ProvinceFindWithDb(keys ...string) map[string]string {
- res := map[string]string{}
- cacheKey := md.OfficialProvinceCacheKey
- err := cache.GetJson(cacheKey, &res)
- if err != nil || len(res) == 0 {
- provinceList, _ := ProvinceGetAll()
- if provinceList == nil {
- return nil
- }
- for _, v := range *provinceList {
- res[v.Id] = v.Name
- }
- cache.SetJson(cacheKey, res, md.CfgCacheTime)
- }
- if len(keys) == 0 {
- return res
- }
- tmp := map[string]string{}
- for _, v := range keys {
- if val, ok := res[v]; ok {
- tmp[v] = val
- } else {
- tmp[v] = ""
- }
- }
- return tmp
- }
|