此代码给出了一个错误:
$post = Post::find($post_id);
$post->deleted_at = null;
$post->save();
这是错误:
Creating default object from empty value
也试过
$post->deleted_at = '';
这给了我同样的错误。
答案 0 :(得分:3)
如果找不到该模型,那么该变量中的空值为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();
}
答案 1 :(得分:1)
您必须确保已成功找到所需的数据库记录。该错误来自您尝试访问空对象上的数据库列。
简单的检查可以避免您的错误:
$post = Post::find($post_id);
if ($post !== null) {
$post->some_date_field = null;
$post->save();
}