Skip to content

GoFrame ORM原生方法 开箱体验 (上)

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第12天,点击查看活动详情

前言

最近一直在用GoFrame(下文简称gf)来开发项目,在熟悉业务逻辑之后就是马不停蹄的撸代码了。

之前整理过结构体和json转换的文章:GoFrame必知必会之Scan:类型转换,今天整理同样比较重要的ORM相关的文章。

gf是支持ORM原生操作的,在ORM链式操作执行不了太过于复杂的SQL操作时,可以交给方法操作来处理。

这篇文章整理原生操作的常用方法,下篇文章根据整理的原生方法整理对应的开箱体验。

常用方法

SQL操作方法,返回原生的标准库sql对象

  1. Query是原始的数据查询方法,返回的是原生的标准库的结果集对象,需要自行解析。
  2. Exec方法用于写入/更新的SQL的操作。
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)

数据表记录查询:

  1. 查询单条记录、查询多条记录、获取记录对象、查询单个字段值(链式操作同理)
  2. 在执行数据查询时推荐使用Get*系列查询方法。
sql
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

数据单条操作

  1. Insert/Replace/Save方法中的data参数支持的数据类型为:string/map/slice/struct/*struct,当传递为slice类型时,自动识别为批量操作,此时batch参数有效。
sql
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新特性介绍

数据修改/删除

sql
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链式操作非常简单且强大,但是业务中总还是有一些逻辑需要使用原生方法实现,化繁为简。

最后

感谢阅读,欢迎大家三连:点赞、收藏、投币(关注)!!!

8e95dac1fd0b2b1ff51c08757667c47a.gif

🚀 学习遇到瓶颈?想进大厂?

看完这篇技术文章,如果还是觉得不够系统,或者想在实战中快速提升?
王中阳的就业陪跑训练营,提供定制化学习路线 + 企业级实战项目 + 简历优化 + 模拟面试。

了解训练营详情