排序没有生效 db := common.DB.Session(&gorm.Session{}) //升序降序 feild := ctx.DefaultQuery("feild", "id") order := ctx.Query("order") if order == "desc" { feild = feild + " DESC" } else { feild = feild + " ASC" } var res *gorm.DB if s == 5 { common.DB.Model(&req).Debug().Where("name LIKE ?", "%"+name+"%").Where("responsible_unit LIKE ?", "%"+unit+"%").Count(&count) res = db.Order(feild).Scopes(Paginate(page, pageSize)).Where("name LIKE ?", "%"+name+"%").Where("responsible_unit LIKE ?", "%"+unit+"%").Find(&lists) } else { common.DB.Model(&req).Where("status=?", s).Where("name LIKE ?", "%"+name+"%").Where("responsible_unit LIKE ?", "%"+unit+"%").Count(&count) res = db.Order(feild).Scopes(Paginate(page, pageSize)).Where("status=?", s).Where("name LIKE ?", "%"+name+"%").Where("responsible_unit LIKE ?", "%"+unit+"%").Find(&lists) }
时间: 2023-07-23 13:14:24 浏览: 38
根据您提供的代码片段,我看到您尝试对数据库查询结果进行排序。在这段代码中,您通过 `db.Order(feild)` 来设置排序字段。
如果排序没有生效,可能有几个原因需要检查:
1. 确保 `feild` 变量的值正确。您可以打印或调试查看 `feild` 的值是否正确。
2. 确保您的数据库表中存在与 `feild` 对应的列名。如果列名不存在或拼写错误,排序将无效。
3. 确保数据库连接和查询语句没有其他错误。您可以通过打印或调试来验证数据库查询是否正确执行。
如果这些步骤都没有解决问题,建议提供更多上下文或错误信息以便更好地帮助您解决问题。
相关问题
改进代码func TracingList(ctx *gin.Context) { resp := models.Response{ Code: 0, Msg: "success", } t, _ := strconv.Atoi(ctx.Query("t")) label, _ := strconv.Atoi(ctx.Query("label")) page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1")) pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10")) code := ctx.Query("code") //设施类型 if len(code) == 0 { resp.Code = 400 resp.Msg = "请输入code值" ctx.JSON(400, resp) return } type Total struct { gorm.Model Type int16 Source int16 Explanation string Label int16 FacilityID string } db := common.DB.Session(&gorm.Session{}) if t < 0 || t > 5 { var req interface{} switch t { case 0: req = []*Total{} case 1: req = []*models.Flaw{} case 2: req = []*models.Issue{} case 3: req = []*models.Record{} case 4: req = []*models.Quality{} case 5: req = []*models.Inspection{} } //查询并分页 if t < 1 || t > 5 { res := db.Scopes(models.Paginate(page, pageSize)).Where("facility_id=?", code).Find(&req) if res.RowsAffected == 0 { resp.Code = 400 resp.Msg = "记录不存在" ctx.JSON(400, resp) return } } else { 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) } else if label < 1 || label > 4 { var req []*Total res := db.Scopes(models.Paginate(page, pageSize)).Raw("SELECT * FROM flaws WHERE label = ? "+ "UNION SELECT * FROM issues WHERE label = ? "+ "UNION SELECT * FROM records WHERE label = ? "+ "UNION SELECT * FROM qualities WHERE label = ? "+ "UNION SELECT * FROM inspections WHERE label = ?", "label", "label", "label", "label", "label").Find(&req) if res.RowsAffected == 0 { resp.Code = 400 resp.Msg = "记录不存在" ctx.JSON(400, resp) return } resp.Data = req ctx.JSON(200, resp) } else { ctx.JSON(400, models.Response{ Code: 400, Msg: "参数有误", }) return } }
以下是改进的代码:
```go
func TracingList(ctx *gin.Context) {
resp := models.Response{
Code: 0,
Msg: "success",
}
code := ctx.Query("code")
if len(code) == 0 {
resp.Code = 400
resp.Msg = "请输入code值"
ctx.JSON(400, resp)
return
}
t, err := strconv.Atoi(ctx.Query("t"))
if err != nil || t < 0 || t > 5 {
resp.Code = 400
resp.Msg = "无效的参数t"
ctx.JSON(400, resp)
return
}
label, err := strconv.Atoi(ctx.Query("label"))
if err != nil || label < 1 || label > 4 {
resp.Code = 400
resp.Msg = "无效的参数label"
ctx.JSON(400, resp)
return
}
page, err := strconv.Atoi(ctx.DefaultQuery("page", "1"))
if err != nil || page < 1 {
resp.Code = 400
resp.Msg = "无效的参数page"
ctx.JSON(400, resp)
return
}
pageSize, err := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))
if err != nil || pageSize < 1 {
resp.Code = 400
resp.Msg = "无效的参数pageSize"
ctx.JSON(400, resp)
return
}
var req interface{}
switch t {
case 0:
req = []*Total{}
case 1:
req = []*models.Flaw{}
case 2:
req = []*models.Issue{}
case 3:
req = []*models.Record{}
case 4:
req = []*models.Quality{}
case 5:
req = []*models.Inspection{}
}
db := common.DB.Session(&gorm.Session{})
res := db.Scopes(models.Paginate(page, pageSize)).Where("facility_id=?", code)
if t >= 1 && t <= 5 {
res = res.Table("flaws").Where("facility_id=?", code).
Or("facility_id=?", code).
Or("facility_id=?", code).
Or("facility_id=?", code).
Or("facility_id=?", code)
}
res.Find(req)
if res.RowsAffected == 0 {
resp.Code = 400
resp.Msg = "记录不存在"
ctx.JSON(400, resp)
return
}
resp.Data = req
ctx.JSON(200, resp)
}
```
主要改进包括:
1. 对输入的参数进行了有效性检查,如 t、label、page 和 pageSize 都需要为正整数,code 不能为空。
2. 使用了 Go 语言内置的错误处理机制,当参数无效时,返回错误信息。
3. 将 SQL 查询语句拆分为两段,根据 t 的值判断使用哪一段,避免了使用 Raw() 方法的安全隐患。
4. 代码结构更加清晰,易于阅读和维护。
func SaveOS() { var data []model.HistoryMessages gorm.DB.Find(&data) file, err := os.Create("data.csv") if err != nil { panic(err) } defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() writer.Write([]string{"SendId", "ReceiveId", "Object", "Media", "Content", "SendTime"}) for _, message := range data { record := []string{ message.SendId, message.ReceiveId, message.Object, message.Media, message.Content, message.SendTime.Format("2006-01-02 15:04:05"), } writer.Write(record) } }帮我把这代码生成的文件使用aes加密,写出完整代码
好的,请参考下面的代码,使用AES加密文件:
```
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/csv"
"os"
"io"
"log"
)
func SaveOS() {
var data []model.HistoryMessages
gorm.DB.Find(&data)
// 创建文件并打开
file, err := os.Create("data.csv")
if err != nil {
panic(err)
}
defer file.Close()
// 创建CSV writer
writer := csv.NewWriter(file)
defer writer.Flush()
// 写入表头
writer.Write([]string{"SendId", "ReceiveId", "Object", "Media", "Content", "SendTime"})
// 写入数据
for _, message := range data {
record := []string{
message.SendId,
message.ReceiveId,
message.Object,
message.Media,
message.Content,
message.SendTime.Format("2006-01-02 15:04:05"),
}
writer.Write(record)
}
// 打开CSV文件并读取数据
csvfile, err := os.Open("data.csv")
if err != nil {
log.Fatalln("Unable to read input file " + "data.csv")
}
defer csvfile.Close()
reader := csv.NewReader(csvfile)
records, err := reader.ReadAll()
if err != nil {
log.Fatalln("Unable to parse file " + "data.csv")
}
// 生成随机密钥和向量
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
panic(err.Error())
}
iv := make([]byte, aes.BlockSize)
if _, err := rand.Read(iv); err != nil {
panic(err.Error())
}
// 创建加密器
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
ciphertext := make([]byte, aes.BlockSize+len(records))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(records))
// 写入加密后的数据和密钥、向量到文件
outfile, err := os.Create("data.enc")
if err != nil {
log.Fatalln("Unable to create output file " + "data.enc")
}
defer outfile.Close()
// 写入密钥和向量
outfile.Write(iv)
outfile.Write(key)
// 写入加密后的数据
_, err = outfile.Write(ciphertext)
if err != nil {
log.Fatalln("Unable to write encrypted data to output file")
}
}
```
注意:这个代码中使用了AES-CTR模式进行加密,同时生成了随机的密钥和向量。加密后的数据保存在" data.enc"文件中,同时也保存了密钥和向量。在解密时,需要使用相同的密钥和向量才能成功解密。