改进代码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)
时间: 2024-01-29 08:04:20 浏览: 103
mw-parse-url:将 req.url 解析为 req.path 和 req.query 的中间件
这段代码可以优化为使用GORM的联合查询(Union)功能,避免使用Raw SQL语句。
可以尝试这样改进代码:
```
err := db.Where("facility_id = ?", code).
Select("id, created_at, updated_at, field1, field2, NULL as field3, NULL as field4, NULL as field5").
Table("flaws").
Union(db.Where("facility_id = ?", code).
Select("id, created_at, updated_at, field1, NULL as field2, field3, field4, NULL as field5").
Table("issues")).
Union(db.Where("facility_id = ?", code).
Select("id, created_at, updated_at, field1, NULL as field2, NULL as field3, NULL as field4, field5").
Table("records")).
Union(db.Where("facility_id = ?", code).
Select("id, created_at, updated_at, field1, field2, NULL as field3, NULL as field4, NULL as field5").
Table("qualities")).
Union(db.Where("facility_id = ?", code).
Select("id, created_at, updated_at, field1, NULL as field2, field3, field4, field5").
Table("inspections")).
Order("created_at desc").
Limit(pageSize).
Offset((page - 1) * pageSize).
Find(&req).Error
```
在这个示例中,我们使用了 `Select` 函数选择每个表中的字段,并将不需要的字段设置为 `NULL`。然后我们使用 `Union` 函数将所有查询合并到一起,并使用 `Order`、`Limit` 和 `Offset` 函数进行分页和排序。
这种方法比使用 `Raw` 函数更安全,因为它可以防止 SQL 注入攻击,并且更易于维护。
阅读全文