|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- package db
-
- import (
- "applet/app/db/model"
- "applet/app/md"
- "applet/app/utils/cache"
- "applet/app/utils/logx"
- )
-
- func CityGetAll() (*[]model.City, error) {
- var CityList []model.City
- if err := Db.Cols("id,name").Find(&CityList); err != nil {
- return nil, logx.Error(err)
- }
- return &CityList, nil
- }
-
- // 获取一条记录
- func CityGetOne(key string) (*model.City, error) {
- var City model.City
-
- if has, err := Db.Where("`id`=?", key).Get(&City); err != nil || has == false {
- if has == false {
- return &City, nil
- }
- return nil, logx.Error(err)
- }
- return &City, nil
- }
-
- func CityGetOneByName(name string) (*model.City, error) {
- var City model.City
- if has, err := Db.Where("name LIKE ?", "%"+name+"%").Get(&City); err != nil || has == false {
- if has == false {
- return &City, nil
- }
- return nil, logx.Error(err)
- }
- return &City, nil
- }
-
- //单条记录获取DB
- func CityGetWithDb(HKey string) string {
- cacheKey := md.OfficialCityCacheKey
- get, err := cache.HGetString(cacheKey, HKey)
- if err != nil || get == "" {
- City, err := CityGetOne(HKey)
- if err != nil || City == nil {
- _ = logx.Error(err)
- return ""
- }
-
- // key是否存在
- cacheKeyExist := false
- if cache.Exists(cacheKey) {
- cacheKeyExist = true
- }
-
- // 设置缓存
- _, err = cache.HSet(cacheKey, HKey, City.Name)
- if err != nil {
- _ = logx.Error(err)
- return ""
- }
- if !cacheKeyExist { // 如果是首次设置 设置过期时间
- _, err := cache.Expire(cacheKey, md.CfgCacheTime)
- if err != nil {
- _ = logx.Error(err)
- return ""
- }
- }
- return City.Name
- }
- return get
- }
-
- func CityFindWithDb(keys ...string) map[string]string {
- res := map[string]string{}
- cacheKey := md.OfficialCityCacheKey
- err := cache.GetJson(cacheKey, &res)
- if err != nil || len(res) == 0 {
- CityList, _ := CityGetAll()
- if CityList == nil {
- return nil
- }
- for _, v := range *CityList {
- 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
- }
|