Laravel 软删除 restore() 错误

50
以下软删除代码对我来说很好用:
$post = Post::find($post_id);
$post->delete();

已更新删除日期字段,但这给了我一个错误:

$post = Post::find($post_id);
$post->restore();

这是错误信息:

exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function restore() on a non-object'

我束手无策。到目前为止,谷歌也没有帮助到我。

3个回答

112

错误显示$post不是一个对象,Laravel在没有使用withTrashed() 的情况下不会返回已经被软删除的记录。

Post::withTrashed()->find($post_id)->restore();

当查询使用软删除的模型时,“已删除”的模型将不会被包括在内...

Laravel 文档 - 软删除


1
运行得很好。谢谢。 - moreirapontocom

5

另一个选项是在已删除的模型中通过特定ID进行搜索:

Post::onlyTrashed()->where('id', $post_id)->restore();

1
评论:在您的答案中添加一些注释和解释会很好。 - H.Hasenack
Khalid,您的见解是要指出当您知道正在寻找已删除的值时,withTrashed是不必要的吗?如果是这样,澄清一下可能会很好。 - lahwran
withTrashed用于恢复已删除和未删除的帖子,onlyTrashed用于仅恢复已删除的帖子。 - jak

0
也许将来有人会用得上。当我们下载被删除的文件时,你可以轻松地使用恢复功能。
Route::post('restore/{exampleModel}', [ExampleController::class, 'restore'])->withTrashed();

public function restore(ExampleModel $exampleModel)
{
        $exampleModel->restore();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接