How do I perform a Mass delete using Laravel 4.1, based on array of ids or objects?(如何使用 Laravel 4.1 基于 id 或对象数组执行批量删除?)
问题描述
我只是想知道是否有可能.
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();
这篇关于如何使用 Laravel 4.1 基于 id 或对象数组执行批量删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Laravel 4.1 基于 id 或对象数组执行批量删除?
基础教程推荐
- 使用 PDO 转义列名 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01