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

2021-12-26 00:00:00 arrays orm php laravel-4 eloquent

我只是想知道是否有可能.

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

推荐答案

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

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

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

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

2) 想通过 ID 快速删除记录?没问题.只需将 ID 传递到删除方法中即可:

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) 如果你想一次删除多个记录的 id,将它们的 id 传递到一个数组中 - 使用以下内容

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

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) 按键删除现有模型

5) Deleting An Existing Model By Key

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

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

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

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

相关文章