此代碼給我一個錯誤: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