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. m := g.DB().Model("user").Hook(gdb.HookHandler{
  2. Select: func(ctx context.Context, in *gdb.HookSelectInput) (result gdb.Result, err error) {
  3. result, err = in.Next(ctx)
  4. if err != nil {
  5. return
  6. }
  7. for i, record := range result {
  8. if !record["birth_day"].IsEmpty() {
  9. age := gtime.Now().Sub(record["birth_day"].GTime()).Hours() / 24 / 365
  10. record["age"] = gvar.New(age)
  11. }
  12. result[i] = record
  13. }
  14. return
  15. },
  16. })
  17. all, err := m.Where("status", "online").OrderAsc(`id`).All()