【问题标题】:Laravel 4 Update DB field to Null - ErrorLaravel 4将数据库字段更新为空 - 错误
【发布时间】:2014-08-29 22:47:30
【问题描述】:

这段代码给了我一个错误:

$post = Post::find($post_id);
$post->deleted_at = null;
$post->save();

这是错误:

Creating default object from empty value

也试过了

$post->deleted_at = '';

这给了我同样的错误。

【问题讨论】:

    标签: mysql laravel laravel-4 eloquent


    【解决方案1】:

    如果它没有找到模型,您将在该变量中包含 null,因此您可以:

    $post = Post::findOrNew($post_id); /// If it doesn't find, it just creates a new model and return it
    
    $post->deleted_at = null;
    
    $post->save();
    

    但如果你真的需要它存在:

    $post = Post::findOrFail($post_id); /// it will raise an exception you can treat after
    
    $post->deleted_at = null;
    
    $post->save();
    

    而且,如果没关系:

    if ($post = Post::find($post_id)) 
    {
        $post->deleted_at = null;
    
        $post->save();
    }
    

    【讨论】:

    • 谢谢。不知道这两个功能。
    【解决方案2】:

    您必须确保您已成功找到您要查找的数据库记录。该错误来自您尝试访问空对象上的数据库列。

    一个简单的检查将避免你的错误:

    $post = Post::find($post_id);
    
    if ($post !== null) {
        $post->some_date_field = null;
        $post->save();
    }
    

    【讨论】:

    • 就是这样。谢谢。我试图返回已被软删除的记录。这将为我解决它:Post::withTrashed()->find($post_id);
    猜你喜欢
    • 2012-07-02
    • 2014-08-19
    • 2018-06-15
    • 2019-05-31
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多