我在我的项目中使用 GORM,我想创建类似数据库管理页面的东西。
要加载记录,我发送带有参数的 GET:
category: "name", // database table name
在服务器上我有下一个代码:
func LoadItems(db *gorm.DB, category string) interface{} {
var items interface{}
loadItems := func(i interface{}) {
err := db.Find(i).Error
if err != nil {
panic(err)
}
items = i
}
switch category {
case "groups":
var records []*models.Groups
loadItems(&records)
case "departments":
var records []*models.Departments
loadItems(&records)
case .....
........
}
return items
}
是否可以替换 switch
因为我有 10 个表并且在记录编辑后我将新数据发送到服务器,我被迫在其他功能中使用 switch
来保存它。
最佳答案
我不熟悉 gorm,但是: 也许将“部门”(作为键)和对应模型类型的变量存储在映射中,然后通过键引用到模型。如果还没有,那么模型必须实现一个通用接口(interface),以便能够将它们存储在一个 map 中。 不过,我不确定这是否是更好的解决方案。也许更容易维护一些,因为只需将新的模型类型添加到 map 中,而不必在代码中的多个位置调整开关。
另一种明显的方法是,将开关外包给一个函数,返回一个通用接口(interface)类型的变量,并在代码的不同位置使用它。那绝对不会更快,但更容易维护。
关于GORM Golang 如何优化这段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30208528/