GoFrame?ORM原生方法操作示例
前言
最近一直在用GoFrame(下文簡稱gf)來開發(fā)項目,在熟悉業(yè)務邏輯之后就是馬不停蹄的擼代碼了。
之前整理過結構體和json轉換的文章:GoFrame必知必會之Scan:類型轉換,今天整理同樣比較重要的ORM相關的文章。
gf是支持ORM原生操作的,在ORM鏈式操作執(zhí)行不了太過于復雜的SQL操作時,可以交給方法操作來處理。
這篇文章整理原生操作的常用方法,下篇文章根據(jù)整理的原生方法整理對應的開箱體驗。
常用方法
SQL操作方法,返回原生的標準庫sql對象
- Query是原始的數(shù)據(jù)查詢方法,返回的是原生的標準庫的結果集對象,需要自行解析。
- Exec方法用于寫入/更新的SQL的操作。
Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) Prepare(ctx context.Context, query string) (*sql.Stmt, error)
數(shù)據(jù)表記錄查詢:
- 查詢單條記錄、查詢多條記錄、獲取記錄對象、查詢單個字段值(鏈式操作同理)
- 在執(zhí)行數(shù)據(jù)查詢時推薦使用Get*系列查詢方法。
GetAll(ctx context.Context, sql string, args ...interface{}) (Result, error) GetOne(ctx context.Context, sql string, args ...interface{}) (Record, error) GetValue(ctx context.Context, sql string, args ...interface{}) (Value, error) GetArray(ctx context.Context, sql string, args ...interface{}) ([]Value, error) GetCount(ctx context.Context, sql string, args ...interface{}) (int, error) GetScan(ctx context.Context, objPointer interface{}, sql string, args ...interface{}) error
數(shù)據(jù)單條操作
Insert/Replace/Save方法中的data參數(shù)支持的數(shù)據(jù)類型為:
string/map/slice/struct/*struct,當傳遞為slice類型時,自動識別為批量操作,此時batch參數(shù)有效。
Insert(ctx context.Context, table string, data interface{}, batch...int) (sql.Result, error) Replace(ctx context.Context, table string, data interface{}, batch...int) (sql.Result, error) Save(ctx context.Context, table string, data interface{}, batch...int) (sql.Result, error)
在這里由衷的感嘆一句:gf確實非常方便。至今記得自己用gorm1.1版本時,困頓于批量插入無法自拔:# Go GORM是時候升級新版本了 2.0新特性介紹
數(shù)據(jù)修改/刪除
Update(ctx context.Context, table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (sql.Result, error)
總結
雖然GoFrame的ORM鏈式操作非常簡單且強大,但是業(yè)務中總還是有一些邏輯需要使用原生方法實現(xiàn),化繁為簡。
以上就是GoFrame ORM原生方法操作示例的詳細內容,更多關于GoFrame ORM原生方法的資料請關注腳本之家其它相關文章!
相關文章
go浮點數(shù)轉字符串保留小數(shù)點后N位的完美解決方法
這篇文章主要介紹了go浮點數(shù)轉字符串保留小數(shù)點后N位解決辦法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05go語言實現(xiàn)的memcache協(xié)議服務的方法
這篇文章主要介紹了go語言實現(xiàn)的memcache協(xié)議服務的方法,實例分析了Go語言使用memcache的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03