您现在的位置是:网站首页> 编程资料编程资料
golang gorm开发架构及写插件示例_Golang_
2023-05-26
367人已围观
简介 golang gorm开发架构及写插件示例_Golang_
1. 开发
1.1. 架构
Gorm使用可链接的API,*gorm.DB是链的桥梁,对于每个链API,它将创建一个新的关系。
db, err := gorm.Open("postgres", "user=gorm dbname=gorm sslmode=disable") // 创建新关系 db = db.Where("name = ?", "jinzhu") // 过滤更多 if SomeCondition { db = db.Where("age = ?", 20) } else { db = db.Where("age = ?", 30) } if YetAnotherCondition { db = db.Where("active = ?", 1) } 当我们开始执行任何操作时,GORM将基于当前的*gorm.DB创建一个新的*gorm.Scope实例
// 执行查询操作 db.First(&user)
并且基于当前操作的类型,它将调用注册的creating, updating, querying, deleting或row_querying回调来运行操作。
对于上面的例子,将调用querying,参考查询回调
1.2. 写插件
GORM本身由Callbacks提供支持,因此您可以根据需要完全自定义GORM
1.2.1. 注册新的callback
func updateCreated(scope *Scope) { if scope.HasColumn("Created") { scope.SetColumn("Created", NowFunc()) } } db.Callback().Create().Register("update_created_at", updateCreated) // 注册Create进程的回调 1.2.2. 删除现有的callback
db.Callback().Create().Remove("gorm:create") // 从Create回调中删除`gorm:create`回调 1.2.3. 替换现有的callback
db.Callback().Create().Replace("gorm:create", newCreateFunction) // 使用新函数`newCreateFunction`替换回调`gorm:create`用于创建过程 1.2.4. 注册callback顺序
db.Callback().Create().Before("gorm:create").Register("update_created_at", updateCreated) db.Callback().Create().After("gorm:create").Register("update_created_at", updateCreated) db.Callback().Query().After("gorm:query").Register("my_plugin:after_query", afterQuery) db.Callback().Delete().After("gorm:delete").Register("my_plugin:after_delete", afterDelete) db.Callback().Update().Before("gorm:update").Register("my_plugin:before_update", beforeUpdate) db.Callback().Create().Before("gorm:create").After("gorm:before_create").Register("my_plugin:before_create", beforeCreate) 1.2.5. 预定义回调
GORM定义了回调以执行其CRUD操作,在开始编写插件之前检查它们。
Row Query callbacks Row Query callbacks将在运行Row或Rows时被调用,默认情况下没有注册的回调,你可以注册一个新的回调:
func updateTableName(scope *gorm.Scope) { scope.Search.Table(scope.TableName() + "_draft") // append `_draft` to table name } db.Callback().RowQuery().Register("publish:update_table_name", updateTableName)以上就是golang gorm开发架构及写插件示例的详细内容,更多关于golang gorm开发架构写插件的资料请关注其它相关文章!
您可能感兴趣的文章:
相关内容
- golang gorm错误处理事务以及日志用法示例_Golang_
- golang gorm的Callbacks事务回滚对象操作示例_Golang_
- Golang协程池gopool设计与实现_Golang_
- golang gorm的预加载及软删硬删的数据操作示例_Golang_
- golang gorm的关系关联实现示例_Golang_
- golang gorm模型结构体的定义示例_Golang_
- Go语言学习之循环语句使用详解_Golang_
- golang gorm框架数据库的连接操作示例_Golang_
- axios gin的GET和POST请求实现示例_Golang_
- golang Gin上传文件返回前端及中间件实现示例_Golang_
