GoFrame?ORM原生方法操作示例
前言
最近一直在用GoFrame(下文簡稱gf)來開發(fā)項目,在熟悉業(yè)務(wù)邏輯之后就是馬不停蹄的擼代碼了。
之前整理過結(jié)構(gòu)體和json轉(zhuǎn)換的文章:GoFrame必知必會之Scan:類型轉(zhuǎn)換,今天整理同樣比較重要的ORM相關(guān)的文章。
gf是支持ORM原生操作的,在ORM鏈式操作執(zhí)行不了太過于復(fù)雜的SQL操作時,可以交給方法操作來處理。
這篇文章整理原生操作的常用方法,下篇文章根據(jù)整理的原生方法整理對應(yīng)的開箱體驗。
常用方法
SQL操作方法,返回原生的標準庫sql對象
- Query是原始的數(shù)據(jù)查詢方法,返回的是原生的標準庫的結(jié)果集對象,需要自行解析。
- 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)
總結(jié)
雖然GoFrame的ORM鏈式操作非常簡單且強大,但是業(yè)務(wù)中總還是有一些邏輯需要使用原生方法實現(xiàn),化繁為簡。
以上就是GoFrame ORM原生方法操作示例的詳細內(nèi)容,更多關(guān)于GoFrame ORM原生方法的資料請關(guān)注腳本之家其它相關(guān)文章!
- GoFrame框架使用避坑指南和實踐干貨
- GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧
- GoFrame?gredis配置文件及配置方法對比
- 適合PHP同學(xué)的GoFrame框架使用體驗及學(xué)習(xí)建議
- GoFrame 框架緩存查詢結(jié)果的示例詳解
- GoFrame錯誤處理常用方法及錯誤碼使用示例
- GoFrame框架Scan類型轉(zhuǎn)換實例
- GoFrame通用類型變量gvar與interface基本使用對比
- GoFrame框架數(shù)據(jù)校驗之校驗對象校驗結(jié)構(gòu)體
- GoLang編程必備:GoFrame?GoLand插件介紹
相關(guān)文章
使用gRPC實現(xiàn)獲取數(shù)據(jù)庫版本
這篇文章主要為大家詳細介紹了如何使用gRPC實現(xiàn)獲取數(shù)據(jù)庫版本,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
更高效的GoLevelDB:shardingdb實現(xiàn)分片和并發(fā)讀寫操作
這篇文章主要介紹了更高效的GoLevelDB:shardingdb實現(xiàn)分片和并發(fā)讀寫操作的相關(guān)資料,需要的朋友可以參考下2023-09-09
Golang實現(xiàn)簡單http服務(wù)器的示例詳解
這篇文章主要為大家詳細介紹了如何利用Golang實現(xiàn)簡單http服務(wù)器,文中的示例代碼講解詳細,對我們學(xué)習(xí)Golang有一定的幫助,需要的可以參考一下2023-03-03
golang struct 實現(xiàn) interface的方法
這篇文章主要介紹了golang struct 實現(xiàn) interface的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07

