Hook特性允许我们对特性的Model绑定CURD钩子处理。

相关定义

相关Hook函数:

type (
	HookFuncSelect func(ctx context.Context, in *HookSelectInput) (result Result, err error)
	HookFuncInsert func(ctx context.Context, in *HookInsertInput) (result sql.Result, err error)
	HookFuncUpdate func(ctx context.Context, in *HookUpdateInput) (result sql.Result, err error)
	HookFuncDelete func(ctx context.Context, in *HookDeleteInput) (result sql.Result, err error)
)

// HookHandler manages all supported hook functions for Model.
type HookHandler struct {
	Select HookFuncSelect
	Insert HookFuncInsert
	Update HookFuncUpdate
	Delete HookFuncDelete
}

Hook注册方法:

// Hook sets the hook functions for current model.
func (m *Model) Hook(hook HookHandler) *Model

使用示例

查询birth_day字段时,同时计算出当前用户的年龄:

// Hook function definition.
var hook = gdb.HookHandler{
	Select: func(ctx context.Context, in *gdb.HookSelectInput) (result gdb.Result, err error) {
		result, err = in.Next(ctx)
		if err != nil {
			return
		}
		for i, record := range result {
			if !record["birth_day"].IsEmpty() {
				age := gtime.Now().Sub(record["birth_day"].GTime()).Hours() / 24 / 365
				record["age"] = gvar.New(age)
			}
			result[i] = record
		}
		return
	},
}
// It registers hook function, creates and returns a new `model`.
model := g.Model("user").Hook(hook)

// The hook function takes effect on each ORM operation when using the `model`.
all, err := model.Where("status", "online").OrderAsc(`id`).All()




Content Menu

  • No labels

3 Comments

  1. 没看明白,Hook方法怎么注册?

  2. package hook
    
    import (
       "context"
       "database/sql"
       "github.com/gogf/gf/v2/database/gdb"
    )
    
    var Curd = gdb.HookHandler{
       Select: func(ctx context.Context, in *gdb.HookSelectInput) (result gdb.Result, err error) {
          result, err = in.Next(ctx)
          return
       },
       Insert: func(ctx context.Context, in *gdb.HookInsertInput) (result sql.Result, err error) {
          result, err = in.Next(ctx)
          return
       },
    
       Update: func(ctx context.Context, in *gdb.HookUpdateInput) (result sql.Result, err error) {
          result, err = in.Next(ctx)
          return
       },
    
       Delete: func(ctx context.Context, in *gdb.HookDeleteInput) (result sql.Result, err error) {
          result, err = in.Next(ctx)
          return
       },
    }
    
    
    
    
    dao.xxx.Ctx(ctx).Data(in).Hook(hook.Curd).InsertAndGetId()
  3. hook切换分表操作的应用实现建议.updateHookHandler,insertHookHandler,deleteHookHandler三者直接对in *gdb.HookXXXInput中的in.Table进行覆写即可完成分表切换(理论).但selectHookHandler中替换in.Table是无效的,在h.Model.db.DoSelect(ctx, h.link, h.Sql, h.Args...)引用的是in.Sql的内容,因此需要对in.Sql中的table信息进行替换,例如执行in.Sql = gstr.Replace(in.Sql, in.Table, gstr.Replace(in.Table, "\"", "")+"_hash1")完成切换分表操作(已验证)