laravel Eloquent ORM delete() method

2022-08-30 09:00:49

嗨,我正在学习拉拉维尔。我使用雄辩的ORM删除方法,但我得到一个不同的结果。不是真或假,而是空。我设置了一个资源路由,在用户控制器中有一个销毁方法。

public function destroy($id){

  $res=User::find($id)->delete();
  if ($res){
    $data=[
    'status'=>'1',
    'msg'=>'success'
  ];
  }else{
    $data=[
    'status'=>'0',
    'msg'=>'fail'
  ];
  return response()->json($data);

但我总是得到一个响应{“status”:“0”,“msg”:“failed”},数据库中的记录被删除。

然后我使用dd($res)。它在页面中显示 null。

但是从课程中我了解到它返回布尔值true或false。

我的代码中是否有任何错误?

你能告诉我一些其他方法,当我从数据库中删除数据时,我可以得到一个布尔结果吗?


答案 1

我认为您可以更改查询并尝试如下:

$res=User::where('id',$id)->delete();

答案 2

在此之前,在拉拉维尔有几种方法。delete

User::find(1)并返回一个实例。User::first()

User::where('id',1)->get并返回实例的集合。User::all()

对模型实例的调用将返回deletetrue/false

$user=User::find(1);
$user->delete(); //returns true/false

对实例集合的调用将返回一个数字,该数字表示已删除的记录数delete

//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)

//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0)  ) 

还有其他删除方法,可以调用如下模型静态方法destroy

$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted

还有一件事,如果你是新手,你可以用它来看到结果,这是更有效的,然后,laravelphp artisan tinkerdd($result)print_r($result);


推荐