我嘗試制作一個 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)
- 1 回答
- 0 關注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消