Laravel 5.2 : delete() 和 forceDelete()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37080168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:44:30  来源:igfitidea点击:

Laravel 5.2 : delete() And forceDelete()

phplaravellaravel-5eloquentlaravel-5.2

提问by Gammer

In My Controller :

在我的控制器中:

public function destroy($id)
{
    $task = Task::findOrFail($id);
    if($task->forceDeleting){
      $task->forceDelete();
    }
    else {
      $task->delete();
    }
      return back();
}

In the above method the elsesection is working but the ifis not working and throws error No query results for model [App\Task]with URIshows http://localhost/Final/public/todo/28

在上述方法中,该else部分正在工作,但if不工作并No query results for model [App\Task]URI显示时引发错误http://localhost/Final/public/todo/28

I am using the same method from views to softDeletesand Permanent Deletes.

我从视图到softDeletes和使用相同的方法Permanent Deletes

{{ Form::open(['method' => 'DELETE', 'route' => ['todo.destroy', $task->id]]) }}
{{ Form::button('<i aria-hidden="true"></i>', array('type' => 'submit', 'class' => 'fa fa fa-trash fa-3x complete-icon')) }}
{{ Form::close() }}

回答by Marcin Nabia?ek

It seems there's no task with id=28. But probably there's also another option. This task is already deleted (using soft deletes), so maybe you should change:

似乎没有 id=28 的任务。但可能还有另一种选择。此任务已被删除(使用软删除),因此也许您应该更改:

$task = Task::findOrFail($id);

into

进入

$task = Task::withTrashed()->findOrFail($id);

EDIT

编辑

In case you want to delete (completely) model that is soft deleted you should use the following code (you should use trashed()method):

如果要删除(完全)软删除的模型,则应使用以下代码(应使用trashed()方法):

public function destroy($id)
{
    $task = Task::withTrashed()->findOrFail($id);
    if(!$task->trashed()){
      $task->delete();
    }
    else {
      $task->forceDelete();
    }
    return back();
}

回答by Gammer

The if($task->deleted_at == null)done the magic.

if($task->deleted_at == null)做的魔力。

public function destroy($id)
{
    $task = Task::withTrashed()->findOrFail($id);
    if($task->deleted_at == null){
      $task->delete();
    }
    else {
      $task->forceDelete();
    }
    return back();
}