laravel Eloquent ORM delete() 方法
我正在学习 Laravel.我使用 Eloquent ORM 删除方法,但得到不同的结果.不是真或假而是空.我设置了一个资源路由,在UsersController中有一个destroy方法.
Hi I am studying laravel. I use Eloquent ORM delete method but I get a different result.Not true or false but null. I set an resource route and there is a destroy method in UsersController.
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"},数据库中的记录被删除了.
But I always get a response {"status":"0","msg":"failed"},the record in the database is deleted.
然后我使用 dd($res) .它在页面中显示为空.
Then I use dd($res) .It shows null in the page.
但是从我学习的课程中,它返回一个布尔值 true 或 false.
But from the course I learn it returns a boolean value true or false.
我的代码有错误吗?
你能告诉我从数据库中删除数据时可以得到布尔结果的其他方法吗?
Can you tell me some other method that I can get a boolean result when I delete data from database?
推荐答案
delete
之前,laravel 有几个方法.
Before delete
, there are several methods in laravel.
User::find(1)
和 User::first()
返回一个实例.
User::find(1)
and User::first()
return an instance.
User::where('id',1)->get
和 User::all()
返回一个实例集合.
User::where('id',1)->get
and User::all()
return a collection of instance.
在模型实例上调用 delete
将返回 true/false
call delete
on an model instance will returns true/false
$user=User::find(1);
$user->delete(); //returns true/false
对实例集合调用 delete
将返回一个数字,表示已删除的记录数
call delete
on a collection of instance will returns a number which represents the number of the records had been deleted
//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
作为模型静态方法,如下所示
Also there are other delete methods, you can call destroy
as a model static method like below
$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
还有一点,如果你是 laravel
的新手,你可以使用 php artisan tinker
来查看结果,这样效率更高,然后 dd($result)
, print_r($result);
One more thing ,if you are new to laravel
,you can use php artisan tinker
to see the result, which is more efficient and then dd($result)
, print_r($result);
相关文章