帮我优化这段代码 // QueryProblemList 查询用户问题列表 func QueryProblemList(page, limit, status int) (map[string]any, error) { if limit == 0 { limit = 10 } dm := db.MysqlDB.Where("status=?", status) var count int64 dm.Model(&ProblemFeedback{}).Count(&count) totalPage := math.Ceil(float64(count) / float64(limit)) offset := (page - 1) * limit var userList []ProblemFeedback var list = make([]map[string]any, 0) dm.Limit(limit).Offset(offset).Order("id desc").Find(&userList) for _, u := range userList { var uInfo WechatUser db.MysqlDB.Find(&uInfo, u.WxID) list = append(list, map[string]any{ "problemID": u.ID, "userID": u.WxID, "nickName": uInfo.Nickname, "mobile": u.Mobile, "email": u.Email, "desc": u.Description, "images": strings.Split(u.Img, ","), "status": u.Status, "createTime": u.CreatedAt.Format(time.DateTime), }) } var info = map[string]any{ "totalCount": count, "totalPage": totalPage, "list": list, } return info, nil }
时间: 2024-03-01 16:54:31 浏览: 61
优化C/C++代码的小技巧
以下是对该函数进行优化后的代码,主要针对数据库查询进行了优化:
```go
// QueryProblemList 查询用户问题列表
func QueryProblemList(page, limit, status int) (map[string]interface{}, error) {
if limit == 0 {
limit = 10
}
var count int64
db.MysqlDB.Model(&ProblemFeedback{}).Where("status = ?", status).Count(&count)
totalPage := int(math.Ceil(float64(count) / float64(limit)))
var userList []struct {
ProblemFeedback
Nickname string `gorm:"column:nickname"`
}
err := db.MysqlDB.Table("problem_feedbacks").
Select("problem_feedbacks.id, problem_feedbacks.wx_id, nickname, problem_feedbacks.mobile, problem_feedbacks.email, problem_feedbacks.description, problem_feedbacks.img, problem_feedbacks.status, problem_feedbacks.created_at").
Joins("left join wechat_users on problem_feedbacks.wx_id = wechat_users.wx_id").
Where("problem_feedbacks.status = ?", status).
Order("problem_feedbacks.id desc").
Limit(limit).
Offset((page - 1) * limit).
Scan(&userList).Error
if err != nil {
return nil, err
}
var list = make([]map[string]interface{}, 0, len(userList))
for _, u := range userList {
list = append(list, map[string]interface{}{
"problemID": u.ID,
"userID": u.WxID,
"nickName": u.Nickname,
"mobile": u.Mobile,
"email": u.Email,
"desc": u.Description,
"images": strings.Split(u.Img, ","),
"status": u.Status,
"createTime": u.CreatedAt.Format("2006-01-02 15:04:05"),
})
}
var info = map[string]interface{}{
"totalCount": count,
"totalPage": totalPage,
"list": list,
}
return info, nil
}
```
对代码的优化主要包括以下几个方面:
1. 将查询条件和查询结果放在同一个语句中,避免多次查询数据库。
2. 使用 `gorm` 的 `Table` 方法来指定表名,避免反射获取表名的开销。
3. 使用 `Scan` 方法来查询结果,避免循环查询数据库的开销。
4. 将 `map[string]any` 类型改为 `map[string]interface{}`,避免使用 `any` 类型的开销。
经过优化后,该函数的查询效率和性能都有了一定的提升,可以更好地满足业务需求。
阅读全文