亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

GORM:通用方式的crud操作符

GORM:通用方式的crud操作符

Go
眼眸繁星 2022-05-23 15:35:15
我嘗試制作一個 Go DAL,為此我主要使用 GORM?,F在我試圖讓我的 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}這里是它們各自的檢索函數(每個函數一個,即使它們完全一樣,除了結構實例化是這里的主要問題):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}
查看完整描述

1 回答

?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

實際上,如果您正確使用它,您的最后一個示例就可以正常工作:


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)


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號