【问题标题】:Laravel Soft Delete restore() ErrorLaravel 软删除 restore() 错误
【发布时间】:2014-10-23 22:08:50
【问题描述】:

以下软删除代码对我来说很好用:

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

deleted_at 字段已更新。但这给了我一个错误:

$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'

我被难住了。到目前为止,Google 没有任何帮助。

【问题讨论】:

    标签: laravel eloquent soft-delete


    【解决方案1】:

    另一种选择是在已删除的模型中搜索特定 ID:

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

    【讨论】:

    • 评论:在你的答案中添加一些评论和解释会很好。
    • khalid,您在这里是否有洞察力指出,当您知道要查找已丢弃的值时, withTrashed 是不必要的?如果是这样,最好澄清一下。
    • withTrashed 用于恢复帖子已删除和帖子未删除,仅用于恢复帖子已删除
    【解决方案2】:

    错误说 $post 是一个非对象,Laravel 不会返回没有 withTrashed() 的垃圾记录

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

    Laravel Docs - Soft Deleting

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

    【讨论】:

    • 像魅力一样工作。谢谢。
    猜你喜欢
    • 2016-03-05
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2015-10-06
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多