php 如何使用 Laravel 4.1 基于 id 或对象数组执行批量删除?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23624630/
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-08-25 16:50:36  来源:igfitidea点击:

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

phparraysormlaravel-4eloquent

提问by arrigonfr

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('some_table')->insert($array);

But as far as I've read, doing the same for deleting doesn't seem to be possible, I'd like to know if anyone know of a way to do something like:

但据我所知,对删除做同样的事情似乎是不可能的,我想知道是否有人知道这样做的方法:

DB::table('some_table')->delete($array);

回答by Gadoma

Many ways of deleting records in Laravel 4.1

Laravel 4.1 中删除记录的多种方式

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

1) 当你想从数据库中删除记录时,只需调用 delete 方法:

$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:

2)想通过ID快速删除记录?没问题。只需将 ID 传递给 delete 方法:

$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

3)如果你想一次通过id删除多条记录,在一个数组中传递它们的id - 使用以下

$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

4)如果你想一次通过id删除多条记录,传递一个用户数组 - 使用以下

        //(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

5) 按键删除现有模型

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:

6) 当然,您也可以对一组模型运行删除查询:

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