简体   繁体   English

laravel Eloquent ORM delete() 方法

[英]laravel Eloquent ORM delete() method

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.嗨,我正在研究 laravel。我使用 Eloquent ORM 删除方法,但我得到了不同的结果。不是 true 或 false,而是 null。我设置了资源路由,UsersController 中有一个 destroy 方法。

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);

But I always get a response {"status":"0","msg":"failed"},the record in the database is deleted.但我总是得到响应 {"status":"0","msg":"failed"},数据库中的记录被删除。

Then I use dd($res).It shows null in the page.然后我使用 dd($res)。它在页面中显示 null。

But from the course I learn it returns a boolean value true or false.但是从我学到的课程中,它返回 boolean 值 true 或 false。

Is there any error in my code?我的代码有什么错误吗?

Can you tell me some other method that I can get a boolean result when I delete data from database?你能告诉我一些其他方法,当我从数据库中删除数据时,我可以获得 boolean 结果吗?

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

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

At first,起初,

You should know that destroy() is correct method for removing an entity directly via object or model and delete() can only be called in query builder.您应该知道destroy()是通过对象或模型直接删除实体的正确方法,并且delete()只能在查询构建器中调用。

In your case, You have not checked if record exists in database or not.在您的情况下,您尚未检查数据库中是否存在记录。 Record can only be deleted if exists.记录只有在存在时才能删除。

So, You can do it like follows.所以,你可以像下面这样做。

$user = User::find($id);
    if($user){
        $destroy = User::destroy(2);
    }

The value or $destroy above will be 0 or 1 on fail or success respectively.上面的值或$destroy在失败或成功时分别为 0 或 1。 So, you can alter the $data array like:因此,您可以更改$data数组,例如:

if ($destroy){

    $data=[
        'status'=>'1',
        'msg'=>'success'
    ];

}else{

    $data=[
        'status'=>'0',
        'msg'=>'fail'
    ];

}

Hope, you understand.希望,你懂的。

Before delete , there are several methods in laravel.delete之前,laravel 中有几个方法。

User::find(1) and User::first() return an instance. User::find(1)User::first()返回一个实例。

User::where('id',1)->get and User::all() return a collection of instance. User::where('id',1)->getUser::all()返回一个实例集合。

call delete on an model instance will returns true/false在模型实例上调用delete将返回true/false

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

call delete on a collection of instance will returns a number which represents the number of the records had been deleted在实例集合上调用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)  ) 

Also there are other delete methods, you can call destroy as a model static method like below还有其他删除方法,您可以调用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

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);还有一件事,如果你是laravel ,你可以使用php artisan tinker来查看结果,这样效率更高,然后dd($result) , print_r($result);

Laravel Eloquent provides destroy() function in which returns boolean value. Laravel Eloquent提供了destroy()函数,其中返回boolean值。 So if a record exists on the database and deleted you'll get true otherwise false .因此,如果数据库中存在记录并被删除,您将得到true否则为false

Here's an example using Laravel Tinker shell .这是一个使用Laravel Tinker shell的例子。

删除操作结果

In this case, your code should look like this:在这种情况下,您的代码应如下所示:

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

More info about Laravel Eloquent Deleting Models有关Laravel Eloquent 删除模型的更多信息

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

You can delete the data using two ways.您可以使用两种方式删除数据。 First, using find Second, using where with model You can try something like this.首先,使用find其次,将where与 model 一起使用 您可以尝试这样的操作。 First:第一的:

User::find($id)->destroy();

Or Second Way或第二种方式

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

Now Please try it will return you True/False result.现在请尝试它会返回真/假结果。

check before delete the user otherwise throws error exeption在删除用户之前检查否则抛出错误异常

$user=User::find($request->id);
  
   if($user)
   {
   // return $user;           <------------------------user exist
       if($user->delete()){
         return 'user deleted';
         }
    else{
       return "something wrong";
        }   

   }
  else{
     return "user not exist";// <--------------------user not exist
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM