改进代码var req []*Total res := db.Scopes(models.Paginate(page, pageSize)).Raw("SELECT * FROM flaws WHERE facility_id = ? "+ "UNION SELECT * FROM issues WHERE facility_id = ? "+ "UNION SELECT * FROM records WHERE facility_id = ? "+ "UNION SELECT * FROM qualities WHERE facility_id = ? "+ "UNION SELECT * FROM inspections WHERE facility_id = ?", code, code, code, code, code).Find(&req) if res.RowsAffected == 0 { resp.Code = 400 resp.Msg = "记录不存在" ctx.JSON(400, resp) return } resp.Data = req ctx.JSON(200, resp)
时间: 2024-01-09 09:04:36 浏览: 86
这段代码可以进行一些改进来提高效率和可读性。首先,可以使用更具可读性的命名来使代码更易于理解。其次,可以使用`ErrRecordNotFound`错误来处理记录不存在的情况,这样代码更易于维护和扩展。最后,可以使用`db.Table`将SQL查询转换为更清晰的代码。
下面是改进后的代码示例:
```
var (
records []*Total
err error
)
err = db.Table("flaws").Where("facility_id = ?", code).Find(&records).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
resp.Code = 500
resp.Msg = "查询失败"
ctx.JSON(500, resp)
return
}
err = db.Table("issues").Where("facility_id = ?", code).Find(&records).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
resp.Code = 500
resp.Msg = "查询失败"
ctx.JSON(500, resp)
return
}
err = db.Table("records").Where("facility_id = ?", code).Find(&records).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
resp.Code = 500
resp.Msg = "查询失败"
ctx.JSON(500, resp)
return
}
err = db.Table("qualities").Where("facility_id = ?", code).Find(&records).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
resp.Code = 500
resp.Msg = "查询失败"
ctx.JSON(500, resp)
return
}
err = db.Table("inspections").Where("facility_id = ?", code).Find(&records).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
resp.Code = 500
resp.Msg = "查询失败"
ctx.JSON(500, resp)
return
}
if len(records) == 0 {
resp.Code = 400
resp.Msg = "记录不存在"
ctx.JSON(400, resp)
return
}
resp.Data = records
ctx.JSON(200, resp)
```
通过这些改进,代码变得更加易于理解和维护,并且可以更清晰地处理错误和异常情况。
阅读全文