cakephp 3 original data in afterSave

回眸只為那壹抹淺笑 提交于 2020-02-15 07:58:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!