我正在尝试为特定表中的更改创建跟踪日志。所以我创建了这个GlobalComponent
:
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\ORM\TableRegistry;
class GlobalComponent extends Component
{
public function traceLog($table, $action, $new_val, $old_val, $user)
{
$tl = TableRegistry::get('TraceLog')->newEntity();
$tl->table_name = $table;
$tl->action_type = $action;
$tl->new_val = $new_val;
$tl->old_val = $old_val;
$tl->user_id = $user;
$tl->created = date("Y-m-d H:i:s");
TableRegistry::get('TraceLog')->save($tl);
}
}
在保存add
之后的Transaction
方法中,我这样调用该方法:
//TraceLog add action
$transaction_array = $transaction->toArray();
foreach ($transaction_array as $propName => $propValue) {
$new_val .= $propName.': '.$propValue.', ';
}
$this->Global->traceLog('Transactions', 'create', $new_val, null, $this->Auth->user('id'));
$transaction
具有与Users
表相似的关联。如何将$proValue
用作用户的username
而不是id
的用户?
又如何在edit
方法中获取脏字段并遍历它们以仅存储脏字段?并从中获得旧价值吗?使用相同的方式:
//TraceLog edit action
$transaction_dirty_array = $transaction->method_to_get_only_dirty_fields();
foreach ($transaction_dirty_array as $propName => $propValue) {
$new_val .= $propName.': '.$propValue.', ';
$old_val .= $propName.': '.$get_old_value.', ';
}
$this->Global->traceLog('Transactions', 'edit', $new_val, $old_val, $this->Auth->user('id'));