我使用audit-stash插件,它适用于我的所有表。但我有一个特殊的功能,用户选择带有复选框的行,然后将特定字段更改为所有这些行。表审计包含一个名为" primary_key"的字段。这似乎不适合这种情况。
在我的控制器中,功能,我把它:
$this->request->data;
$data = $this->request->data;
if($this->request->is(['patch', 'post', 'put']))
{
$ids = $this->request->data('data.AssetsAssignations.id');
$room_id = $this->request->data('room_id');
$this->AssetsAssignations->updateAll(
['room_id ' => $room_id ],
['id IN' => $ids]
);
}
在我的表格中,我使用了这个:
$this->addBehavior('AuditStash.AuditLog');
有人告诉我,对于audit-stash没有办法解决这个问题,因为updateAll通过直接向数据库发送查询来绕过模型回调。
如果我需要保留日志,建议我逐个更新记录。
如何将updateAll()代码转换为Save()循环?
这个尝试对我来说不起作用,使用save()和saveMany():
$this->request->data;
$data = $this->request->data;
if($this->request->is(['patch', 'post', 'put']))
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
foreach($ids as $id) {
$this->AssetsAssignations->saveMany(
['asset_status_id ' => $asset_status_id ]
);
}
}
提前感谢。
答案 0 :(得分:1)
感谢Greg,这段代码对我有用:
use Cake\ORM\TableRegistry;
...
if($this->request->is(['patch', 'post', 'put']))
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$assetsAssignationsTable = TableRegistry::get('AssetsAssignations');
foreach($ids as $id) {
$assetsAssignation = $assetsAssignationsTable->get($id); // Return assetsAssignation with id
$assetsAssignation->asset_status_id = $asset_status_id;
$assetsAssignationsTable->save($assetsAssignation);
}
}
答案 1 :(得分:1)
实际上,您不必为每个ID调用get($id)
。这从表中获取实体并导致大量无用的查询
if($this->request->is(['patch', 'post', 'put']))
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$assetsAssignationsTable = TableRegistry::get('AssetsAssignations');
foreach($ids as $id) {
$assetsAssignation = $assetsAssignationsTable->newEntity(); // returns an empty entity
$assetsAssignation->id = $id; // assign the id to the entity
$assetsAssignation->asset_status_id = $asset_status_id;
$assetsAssignationsTable->save($assetsAssignation);
}
}