go - GORM:通用运算符

标签 go crud data-access-layer go-gorm

我尝试制作Go DAL,为此我主要使用GORM。

现在,我试图使我的DAL尽可能抽象,以便能够查询许多表。

问题是我必须对每个表结构重复我自己-数据库的反射。

让我们举个例子:

这是两个结构,数据库中每个表一个:

type Cad_check_status struct {
    Id int
    Status_code int
    Last_update Timestamp
    Path string
    Ref_num int
    System_code int
}

type Cad_check_errors struct {
    Id int
    check_status int
    error_code Timestamp
}

这里是它们各自的Retrieve函数(每个函数一个,即使它们完全相同,除了struct实例化是这里的主要问题):
func StatusRetrieve(db *CDb, keyval map[string]interface{}) ([]byte, error){
    atts :=  []Cad_check_status{} // <===== this is my problem, the only difference between the two functions
    errors := db.Where(keyval).Find(&atts).GetErrors()
    err := HandleDBErrors(errors)
    if err != nil {
        return nil, err
    }
    b, _ := json.Marshal(atts)
    return b, nil
  }

func ErrorsRetrieve(db *CDb, keyval map[string]interface{}) ([]byte, error){
    atts :=  []Cad_check_errors{} // <=== my problem again, the rest is the same
    errors := db.Where(keyval).Find(&atts).GetErrors()
    err := HandleDBErrors(errors)
    if err != nil {
        return nil, err
    }
    b, _ := json.Marshal(atts)
    return b, nil
}

到目前为止,我试图做这样的事情:
func Retrieve (tableStruct interface{}, db *CDb, keyval map[string]interface{})([]byte, error) {
    atts :=  []tableStruct{} //<=== but of course this is IMPOSSIBLE ! but you got the idea....
    errors := db.Where(keyval).Find(&atts).GetErrors()
    err := HandleDBErrors(errors)
    if err != nil {
        return nil, err
    }
    b, _ := json.Marshal(atts)
    return b, nil
}

最佳答案

实际上,如果正确使用最后一个示例,则效果很好:

func Retrieve (atts interface{}, db *CDb, keyval map[string]interface{})([]byte, error) {
    errors := db.Where(keyval).Find(atts).GetErrors()
    err := HandleDBErrors(errors)
    if err != nil {
        return nil, err
    }
    b, _ := json.Marshal(atts)
    return b, nil
}

var values []Cad_check_status
json,err := Retrieve(&values, db, keyval)

关于go - GORM:通用运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60728022/

相关文章:

golang 在嵌套结构中初始化内部结构对象

arrays - 在 Go 中初始化数组时使用 spread

php - Codeigniter 模型未插入值

c# - DAL中的Entity Framework Repository Pattern,如何实现更新功能?

c# - 从 DAL 返回数据对象

c# - 如何使用Dapper获取存储过程的返回值?

go - 使用该结构的内部函数检查映射中是否存在值

amazon-web-services - 转到 AWS SQS SDK : How to check if session is connected/disconnected

entity-framework - 基本 F#/ Entity Framework /通用函数

javascript - 未使用模态 Bootstrap 和 codeigniter 插入数据