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

相关定义

相关Hook函数:

  1. type (
  2. HookFuncSelect func(ctx context.Context, in *HookSelectInput) (result Result, err error)
  3. HookFuncInsert func(ctx context.Context, in *HookInsertInput) (result sql.Result, err error)
  4. HookFuncUpdate func(ctx context.Context, in *HookUpdateInput) (result sql.Result, err error)
  5. HookFuncDelete func(ctx context.Context, in *HookDeleteInput) (result sql.Result, err error)
  6. )
  7. // HookHandler manages all supported hook functions for Model.
  8. type HookHandler struct {
  9. Select HookFuncSelect
  10. Insert HookFuncInsert
  11. Update HookFuncUpdate
  12. Delete HookFuncDelete
  13. }

Hook注册方法:

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

使用示例

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

  1. // Hook function definition.
  2. var hook = gdb.HookHandler{
  3. Select: func(ctx context.Context, in *gdb.HookSelectInput) (result gdb.Result, err error) {
  4. result, err = in.Next(ctx)
  5. if err != nil {
  6. return
  7. }
  8. for i, record := range result {
  9. if !record["birth_day"].IsEmpty() {
  10. age := gtime.Now().Sub(record["birth_day"].GTime()).Hours() / 24 / 365
  11. record["age"] = gvar.New(age)
  12. }
  13. result[i] = record
  14. }
  15. return
  16. },
  17. }
  18. // It registers hook function, creates and returns a new `model`.
  19. model := g.Model("user").Hook(hook)
  20. // The hook function takes effect on each ORM operation when using the `model`.
  21. all, err := model.Where("status", "online").OrderAsc(`id`).All()