Cakephp 3松饼/垃圾软删除插件时restoreTrash显示错误“找不到书籍”

1u4esq0p  于 2022-11-12  发布在  PHP
关注(0)|答案(1)|浏览(110)

我使用muffin/trash CakePHP 3.* 插件进行了一次软删除。我成功地软删除了我的书,但当我尝试恢复时,我得到了以下错误:
在表“books”中未找到记录
这是我的控制器文件(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>
au9on6nz

au9on6nz1#

由于数据已经被删除(软删除),我们需要添加'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']);
    }

相关问题