1. 开发
1.1. 架构
*gorm.DB
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.DB*gorm.Scope
// 执行查询操作 db.First(&user)
creatingupdatingqueryingdeletingrow_querying
querying
1.2. 写插件
Callbacks
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操作,在开始编写插件之前检查它们。
RowRows
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开发架构写插件的资料请关注源码搜藏网其它相关文章!