我使用松饼/垃圾cakephp 3. *插件进行软删除。我成功软删除了我的书,但是当我还原时,出现以下错误:
在“书”表中找不到记录
这是我的控制器文件(BooksController.php):
public function restoreBook($id = null)
{
$this->request->allowMethod(['post', 'put']);
$book = $this->Books->get($id);
if ($this->Books->restoreTrash($book)) {
$this->Flash->success(__('The book has been restored.'));
} else {
$this->Flash->error(__('The book could not be restored. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
这是我的视图文件(Books / index.ctp),在这里我调用restoreBook函数:
<td class="actions">
<?php if (!$book->deleted) : ?>
<?= $this->Html->link(__('View'), ['action' => 'view', $book->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $book->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $book->id], ['confirm' => __('Are you sure you want to delete # {0}?', $book->id)]) ?>
<?php endif; ?>
<?php if ($book->deleted) : ?>
<?= $this->Form->postLink(__('Restore'), ['action' => 'restoreBook', $book->id], ['confirm' => __('Are you sure you want to restore # {0}?', $book->id)]) ?>
<?php endif; ?>
</td>
答案 0 :(得分:0)
由于数据已被删除(软删除),因此我们需要添加“ withTrashed”来查找数据:
public function restoreBook($id = null)
{
$this->request->allowMethod(['post', 'put']);
//must add 'withTrashed' to find the deleted data
$book = $this->Books->find('withTrashed')->where(['id =' => $id])->first();
if ($this->Books->restoreTrash($book)) {
$this->Flash->success(__('The book has been restored.'));
} else {
$this->Flash->error(__('The book could not be restored. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}