func GetUsersPaged(c *gin.Context) { // 获取分页参数 page, _ :=…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
func GetUsersPaged(c *gin.Context) { // 获取分页参数 page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10")) offset := (page - 1) * pageSize
// 查询用户总数
var total int
err := dao.GetLocalPool().QueryRow(
context.Background(),
"SELECT COUNT(*) FROM users WHERE status = 'active'",
).Scan(&total)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户总数失败"})
return
}
// 查询用户数据
rows, err := dao.GetLocalPool().Query(
context.Background(),
`SELECT
uuid, wechat_openid, user_name, phone, sex, age,
vip_level, created_at, vip_expiry_date, num_samples
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT $1 OFFSET $2`,
pageSize, offset,
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户列表失败"})
return
}
defer rows.Close()
// 处理用户数据
users := make([]gin.H, 0)
uuids := make([]string, 0)
for rows.Next() {
var (
u model.User
vipExpiryDate *time.Time
)
err := rows.Scan(
&u.UUID, &u.WechatOpenID, &u.UserName, &u.Phone, &u.Sex, &u.Age,
&u.VipLevel, &u.CreatedAt, &vipExpiryDate, &u.NumSamples,
)
if err != nil {
log.Printf("解析用户数据失败: %v", err)
continue
}
if vipExpiryDate != nil {
u.VipExpiryDate = *vipExpiryDate
}
users = append(users, gin.H{
"uuid": u.UUID,
"openid": u.WechatOpenID,
"name": u.UserName,
"phone": u.Phone,
"sex": u.Sex,
"age": u.Age,
"vip_level": u.VipLevel,
"created_at": u.CreatedAt,
"vip_expiry": u.VipExpiryDate,
"sample_count": u.NumSamples,
})
uuids = append(uuids, u.UUID)
}
// 批量查询样品信息
sampleMap := make(map[string][]model.Sample) // 使用 string 类型作为键
if len(uuids) > 0 {
sampleRows, err := dao.GetLocalPool().Query(
context.Background(),
`SELECT
uuid, sample_id, report_type, created_at, report_status
FROM samples
WHERE uuid = ANY($1)
ORDER BY created_at DESC`,
uuids, // 传递用户UUID字符串数组
)
if err == nil {
defer sampleRows.Close()
for sampleRows.Next() {
var s model.Sample
if err := sampleRows.Scan(
&s.UUID, &s.SampleID, &s.ReportType, &s.CreatedAt, &s.ReportStatus,
); err == nil {
// 直接使用用户UUID作为键 (string类型)
sampleMap[s.UUID] = append(sampleMap[s.UUID], s)
} else {
log.Printf("解析样品行失败: %v", err)
}
}
} else {
log.Printf("查询样品失败: %v", err)
}
}
// 合并用户和样品数据
result := make([]gin.H, len(users))
for i, user := range users {
uID := user["uuid"].(string) // 确保使用string类型
samples := sampleMap[uID] // 直接匹配字符串键
user["samples"] = samples
result[i] = user
}
c.JSON(http.StatusOK, gin.H{
"total": total,
"page": page,
"data": result,
})
给你1000美元作为小费,debug代码,目前get到的数据是: { "data": [], "page": 1, "total": 397 }
看代码逻辑,问题很可能出在最后的数据合并部分。让我帮你调试:
func GetUsersPaged(c *gin.Context) {
// 获取分页参数
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
offset := (page - 1) * pageSize
// 查询用户总数
var total int
err := dao.GetLocalPool().QueryRow(
context.Background(),
"SELECT COUNT(*) FROM users WHERE status = 'active'",
).Scan(&total)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户总数失败"})
return
}
// 查询用户数据
rows, err := dao.GetLocalPool().Query(
context.Background(),
`SELECT
uuid, wechat_openid, user_name, phone, sex, age,
vip_level, created_at, vip_expiry_date, num_samples
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT $1 OFFSET $2`,
pageSize, offset,
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户列表失败"})
return
}
defer rows.Close()
// 处理用户数据
users := make([]gin.H, 0)
uuids := make([]string, 0)
for rows.Next() {
var (
u model.User
vipExpiryDate *time.Time
)
err := rows.Scan(
&u.UUID, &u.WechatOpenID, &u.UserName, &u.Phone, &u.Sex, &u.Age,
&u.VipLevel, &u.CreatedAt, &vipExpiryDate, &u.NumSamples,
)
if err != nil {
log.Printf("解析用户数据失败: %v", err)
continue
}
if vipExpiryDate != nil {
u.VipExpiryDate = *vipExpiryDate
}
users = append(users, gin.H{
"uuid": u.UUID,
"openid": u.WechatOpenID,
"name": u.UserName,
"phone": u.Phone,
"sex": u.Sex,
"age": u.Age,
"vip_level": u.VipLevel,
"created_at": u.CreatedAt,
"vip_expiry": u.VipExpiryDate,
"sample_count": u.NumSamples,
})
uuids = append(uuids, u.UUID)
}
// 添加调试日志
log.Printf("查询到的用户数: %d", len(users))
// 批量查询样品信息
sampleMap := make(map[string][]model.Sample)
if len(uuids) > 0 {
sampleRows, err := dao.GetLocalPool().Query(
context.Background(),
`SELECT
uuid, sample_id, report_type, created_at, report_status
FROM samples
WHERE uuid = ANY($1)
ORDER BY created_at DESC`,
uuids,
)
if err == nil {
defer sampleRows.Close()
for sampleRows.Next() {
var s model.Sample
if err := sampleRows.Scan(
&s.UUID, &s.SampleID, &s.ReportType, &s.CreatedAt, &s.ReportStatus,
); err == nil {
sampleMap[s.UUID] = append(sampleMap[s.UUID], s)
} else {
log.Printf("解析样品行失败: %v", err)
}
}
} else {
log.Printf("查询样品失败: %v", err)
}
}
// 修复:直接返回users,不需要重新创建result
// 为每个用户添加samples字段
for i := range users {
uID := users[i]["uuid"].(string)
if samples, ok := sampleMap[uID]; ok {
users[i]["samples"] = samples
} else {
users[i]["samples"] = []model.Sample{} // 确保有空数组而不是nil
}
}
c.JSON(http.StatusOK, gin.H{
"total": total,
"page": page,
"data": users, // 直接返回users而不是result
})
}
主要问题在于:
result 切片,但是在循环中你使用的是 users 切片的值,而不是引用user["samples"] = samples 时,实际上是在修改循环变量的副本,而不是原始的 users 切片中的元素修复方案是直接在 users 切片上操作,使用索引访问来确保修改的是原始数据。
另外,我还添加了一些改进:
samples 数组,而不是 nil如果问题仍然存在,请检查:
status = 'active' 的用户