2014-08-29 128 views

回答

1

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

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

$post = Post::find($post_id); 

if ($post !== null) { 
    $post->some_date_field = null; 
    $post->save(); 
} 
+0

就是这样。谢谢。我试图返回一个被软删除的记录。这将为我解决它:'Post :: withTrashed() - > find($ post_id);' – sterfry68 2014-08-29 23:06:14

3

如果它没有找到你的模型将在该变量为空,所以您可以:

$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(); 
} 
+0

谢谢。没有意识到这两个功能。 – sterfry68 2014-08-29 23:09:21