laravel批量更新多条记录,可防止SQL注入
写在前面
熟悉laravel的童鞋都知道,laravel有批量一次性插入多条记录,却没有一次性按条件更新多条记录。
是否羡慕thinkphp的saveAll,是否羡慕ci的update_batch,但如此优雅的laravel怎么就没有类似的批量更新的方法呢?
高手在民间
Google了一下,发现stackoverflow( https://stackoverflow.com/que... )上已经有人写好了,但是并不能防止sql注入。
本篇文章,结合laravel的Eloquent做了调整,可有效防止sql注入。
<?php namespace App\Models; use DB; use Illuminate\Database\Eloquent\Model; /** * 学生表模型 */ class Students extends Model { protected $table = 'students'; //批量更新 public function updateBatch($multipleData = []) { try { if (empty($multipleData)) { throw new \Exception("数据不能为空"); } $tableName = DB::getTablePrefix() . $this->getTable(); // 表名 $firstRow = current($multipleData); $updateColumn = array_keys($firstRow); // 默认以id为条件更新,如果没有ID则以第一个字段为条件 $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn); unset($updateColumn[0]); // 拼接sql语句 $updateSql = "UPDATE " . $tableName . " SET "; $sets = []; $bindings = []; foreach ($updateColumn as $uColumn) { $setSql = "`" . $uColumn . "` = CASE "; foreach ($multipleData as $data) { $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? "; $bindings[] = $data[$referenceColumn]; $bindings[] = $data[$uColumn]; } $setSql .= "ELSE `" . $uColumn . "` END "; $sets[] = $setSql; } $updateSql .= implode(', ', $sets); $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all(); $bindings = array_merge($bindings, $whereIn); $whereIn = rtrim(str_repeat('?,', count($whereIn)), ','); $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")"; // 传入预处理sql语句和对应绑定数据 return DB::update($updateSql, $bindings); } catch (\Exception $e) { return false; } } }
可以根据自己的需求再做调整,下面是用法实例:
// 要批量更新的数组 $students = [ ['id' => 1, 'name' => '张三', 'email' => '[email protected]'], ['id' => 2, 'name' => '李四', 'email' => '[email protected]'], ]; // 批量更新 app(Students::class)->updateBatch($students);
生成的SQL语句如下:
UPDATE pre_students SET NAME = CASE WHEN id = 1 THEN '张三' WHEN id = 2 THEN '李四' ELSE NAME END, email = CASE WHEN id = 1 THEN '[email protected]' WHEN id = 2 THEN '[email protected]' ELSE email END WHERE id IN (1, 2)
是不是效率又提高了一大截呢~
相关推荐
ALiDan 2020-07-27
qshpeng 2020-07-26
世樹 2020-07-17
chenjiazhu 2020-07-08
一对儿程序猿 2020-07-04
明月清风精进不止 2020-06-13
godfather 2020-06-13
ItBJLan 2020-06-11
tanrong 2020-06-11
ALiDan 2020-06-11
码墨 2020-06-09
世樹 2020-06-05
lt云飞扬gt 2020-06-03
godfather 2020-06-03
qshpeng 2020-05-11
明月清风精进不止 2020-05-07
gwn00 2020-05-07