此代码给我一个错误:Laravel 4更新数据库字段设置为null - 错误
$post = Post::find($post_id);
$post->deleted_at = null;
$post->save();
这里的错误:
Creating default object from empty value
也试过
$post->deleted_at = '';
这给了我的同样的错误。
此代码给我一个错误:Laravel 4更新数据库字段设置为null - 错误
$post = Post::find($post_id);
$post->deleted_at = null;
$post->save();
这里的错误:
Creating default object from empty value
也试过
$post->deleted_at = '';
这给了我的同样的错误。
您必须确保您成功找到了您要查找的数据库记录。错误来自您尝试访问空对象上的数据库列。
一个简单的检查将避免你的错误:
$post = Post::find($post_id);
if ($post !== null) {
$post->some_date_field = null;
$post->save();
}
如果它没有找到你的模型将在该变量为空,所以您可以:
$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();
}
谢谢。没有意识到这两个功能。 – sterfry68 2014-08-29 23:09:21
就是这样。谢谢。我试图返回一个被软删除的记录。这将为我解决它:'Post :: withTrashed() - > find($ post_id);' – sterfry68 2014-08-29 23:06:14