问题
Is there any way to access original data in afterSave? I would like to log the changes on important data.
With $entity->isNew() I could check if it was an insert or an update, but how can I get what changed?
回答1:
You can access the original values via Entity::getOriginal()
or Entity::extractOriginal()
. If you want to get all changed fields, combine the latter one with Entity::visibleProperties()
, something like:
debug($entity->extractOriginal($entity->visibleProperties()));
This should return the original values of all changed fields.
See also
- http://api.cakephp.org/3.0/class-Cake.Datasource.EntityTrait.html#_extractOriginal
- http://api.cakephp.org/3.0/class-Cake.Datasource.EntityTrait.html#_getOriginal
- http://api.cakephp.org/3.0/class-Cake.Datasource.EntityInterface.html#_visibleProperties
回答2:
As of CakePHP 3.0.4, you can either use Entity::extractOriginal(), which will return the original value of any field, whether it has changed or not, or use Entity::extractOriginalChanged(), which will only return changed fields.
With this update, to reproduce the behaviour described in the accepted answer, you will thus need something like:
public function afterSave(Event $event, Entity $entity, $options)
{
debug($entity->extractOriginalChanged($entity->visibleProperties()));
}
See CakePHP 3.0.4 Release Notes, stating:
EntityTrait::extractOriginal() now behaves consistently with extract(). Both methods now include all named properties [...] A new method extractOriginalChanged() can be used to extract only the original values of changed attributes.
来源:https://stackoverflow.com/questions/26548511/cakephp-3-original-data-in-aftersave