laravel 批量修改数据

首页 / 正文
 public function UpdateAll(string $tableName, array $info)
    {
        try {
            if (count($info) > 0) {
                $firstRow        = current($info);
                $updateColumn    = array_keys($firstRow);
                $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
                unset($updateColumn[0]);
                $updateSql = "UPDATE " . $tableName . " SET ";
                $sets      = [];
                $bindings  = [];
                foreach ($updateColumn as $uColumn) {
                    $setSql = "`" . $uColumn . "` = CASE ";
                    foreach ($info as $data) {
                        $setSql     .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                        $bindings[] = $data[$referenceColumn];
                        $bindings[] = $data[$uColumn];
                    }
                    $setSql .= "ELSE `" . $uColumn . "` END ";
                    $sets[] = $setSql;
                }
                $updateSql .= implode(', ', $sets);
                $whereIn   = collect($info)->pluck($referenceColumn)->values()->all();
                $bindings  = array_merge($bindings, $whereIn);
                $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
                $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
                return DB::update($updateSql, $bindings);
            }
            return 0;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

调用

  $info = [
                "id"=>$query->id, //id必传
                "consumption_total" => $consumption_total,
                "copy_total"=> $copy_total,
                "copy_cost_total"=> $copy_cost_total,
                "powder_total"=> $powder_total,
                "powder_cost_total"=> $powder_cost_total,
                "powder_rate_total"=> $powder_rate_total,
            ];
  $this->UpdateAll('your_table',info);
打赏
评论区
头像