laravle按不同条件批量更新不同数据记录一下
laravel中DB类中支持批量插入但是没有批量更新语句
如果当需要批量修改数据时,如果用循环来一条一条更新的话极大的消耗资源
下面为批量更新方法,建议分组执行 一组10-20条记录同时更新
/**
* 批量更新
* @param string $whereColumn 条件字段 最好用id主键
* @param array $rows 批量修改的数据 每一行中必须包含条件列与值 例如 $rows = [['id'=>1,'image'=>'xxx','name'=>'xxx'],['id'=>2,'image'=>'xxx','name'=>'xxx','info'=>'xxxx'],['id'=>3,'其他列1'=>'xxx','其他列2'=>'xxx','其他列3'=>'xxxx']] 每行可修改不同数据
* @return false|int 成功返回影响行数 失败返回false
* @throws \Exception
*/
public function updateBatch(string $whereColumn = 'id', array $rows = [])
{
if (empty($rows)) {
throw new StatusTagException("data_notfound");
}
$tableName = DB::getTablePrefix() . $this->getTable(); // 表名
// 取出所有需要更新的列
$updateColumn = [];
foreach ($rows as $row){
$updateColumn = array_merge($updateColumn,array_keys($row));
}
// 去重复
$updateColumn = array_unique($updateColumn);
// 拼接sql语句
$updateSql = "UPDATE " . $tableName . " SET ";
$sets = [];
$bindings = [];
$isExists =<