How do I perform a Mass delete using Laravel 4.1, based on array of ids or objects?

后端 未结 1 401
执念已碎
执念已碎 2020-12-28 16:38

I just wanted to know if it\'s possible.

I know when you have multiple rows to insert, you can just build an array and do something like:

DB::table(\         


        
1条回答
  •  攒了一身酷
    2020-12-28 17:22

    Many ways of deleting records in Laravel 4.1

    1) When you want to delete records from your database, simply call the delete method:

    $affected = DB::table('users')->where('id', '=', 1)->delete();
    

    2) Want to quickly delete a record by its ID? No problem. Just pass the ID into the delete method:

    $affected = DB::table('users')->delete(1);
    

    3) If you want to delete multiple records by id at once, passing their ids in an array - use the following

    $users_to_delete = array(1, 2, 3);
    DB::table('users')->whereIn('id', $users_to_delete)->delete(); 
    

    4) If you want to delete multiple records by id at once, passing an array of users - use the following

            //(case A) User fields indexed by number 0,1,2..
            $users_to_delete = array(
               '0'=> array('1','Frank','Smith','Whatever'), 
               '1'=> array('5','John','Johnson','Whateverelse'),
            );
    
            $ids_to_delete = array_map(function($item){ return $item[0]; }, $users_to_delete);
    
            DB::table('users')->whereIn('id', $ids_to_delete)->delete(); 
    
            //(case B) User fields indexed by key
            $users_to_delete = array(
               '0'=> array('id'=>'1','name'=>'Frank','surname'=>'Smith','title'=>'Whatever'), 
               '1'=> array('id'=>'5','name'=>'John','surname'=>'Johnson','title'=>'Whateverelse'),
            );
    
            $ids_to_delete = array_map(function($item){ return $item['id']; }, $users_to_delete);
    
            DB::table('users')->whereIn('id', $ids_to_delete)->delete(); 
    

    5) Deleting An Existing Model By Key

    User::destroy(1);
    User::destroy(array(1, 2, 3));
    User::destroy(1, 2, 3);
    

    6) Of course, you may also run a delete query on a set of models:

    $affectedRows = User::where('votes', '>', 100)->delete();
    

    0 讨论(0)
提交回复
热议问题