laravel批量更新多条记录

写在前面

熟悉laravel的童鞋都知道,laravel有批量一次性插入多条记录,却没有一次性按条件更新多条记录。

是否羡慕thinkphp的saveAll,是否羡慕ci的update_batch,但如此优雅的laravel怎么就没有类似的批量更新的方法呢?

高手在民间

Google了一下,发现stackoverflow( https://stackoverflow.com/questions/26133977/laravel-bulk-update )上已经有人写好了,但是并不能防止sql注入。

本篇文章,结合laravel的Eloquent做了调整,可有效防止sql注入。

 

//写在模型里

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)
	

以上是转载自https://www.tech1024.com/collect/3/2950.html

本人使用体会,若数据很多,SQL语句太长了也影响速度,需要把大数组拆块执行,速度会再提高三五倍!

            $chunk_datas = array_chunk($sdutents, 200, true);
            foreach ($chunk_datas as $chunk_data) {

                app(RunScore::class)->updateBatch($chunk_data);
            }

 

你可能感兴趣的:(PHP)