This repository has been archived on 2022-04-14. You can view files and clone it, but cannot push or open issues or pull requests.
manual-zh-CN/chapter-12/README.md
2020-03-24 09:23:34 +08:00

65 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 事件
xorm 支持两种方式的事件,一种是在 Struct中的特定方法来作为事件的方法一种是在执行语句的过程中执行事件。
在Struct中作为成员方法的事件如下
* BeforeInsert()
在将此struct插入到数据库之前执行
* BeforeUpdate()
在将此struct更新到数据库之前执行
* BeforeDelete()
在将此struct对应的条件数据从数据库删除之前执行
* `func BeforeSet(name string, cell xorm.Cell)`
在 Get 或 Find 方法中当数据已经从数据库查询出来而在设置到结构体之前调用name为数据库字段名称cell为数据库中的字段值。
* `func AfterSet(name string, cell xorm.Cell)`
在 Get 或 Find 方法中当数据已经从数据库查询出来而在设置到结构体之后调用name为数据库字段名称cell为数据库中的字段值。
* AfterInsert()
在将此struct成功插入到数据库之后执行
* AfterUpdate()
在将此struct成功更新到数据库之后执行
* AfterDelete()
在将此struct对应的条件数据成功从数据库删除之后执行
在语句执行过程中的事件方法为:
* Before(beforeFunc interface{})
临时执行某个方法之前执行
```Go
before := func(bean interface{}){
fmt.Println("before", bean)
}
engine.Before(before).Insert(&obj)
```
* After(afterFunc interface{})
临时执行某个方法之后执行
```Go
after := func(bean interface{}){
fmt.Println("after", bean)
}
engine.After(after).Insert(&obj)
```
其中beforeFunc和afterFunc的原型为func(bean interface{}).