Batch update data function of Laravel framework study notes

  • 2021-12-11 17:25:56
  • OfStack

In this paper, an example is given to describe the batch updating data function of Laravel framework. Share it for your reference, as follows:

Preface

Last week, the company's competition ended with tears... 1 VPS with 2 cores and 4G completely jumped... and was collectively grabbed by the boss. Next month's competition will start again, so now take the time to upgrade the server, optimize the code and SQL, just saw that there are more than 1,000 update statements in the ranking, which is too unbearable, so I found resources in google, found a way to update data in batches, and recorded 1.

Code


//from https://github.com/mavinoo/laravelBatch
static function batchUpdate($model, array $values, $index = null){
  $final = [];
  $ids = [];
  if (!count($values)) {
    return false;
  }
  if (!isset($index) || empty($index)) {
    $index = $model->getKeyName();
  }
  foreach ($values as $key => $val) {
    $ids[] = $val[$index];
    foreach (array_keys($val) as $field) {
      if ($field !== $index) {
        $value = (is_null($val[$field]) ? 'NULL' : '"' . self::mysql_escape($val[$field]) . '"');
        $final[$field][] = 'WHEN `' . $index . '` = "' . $val[$index] . '" THEN ' . $value . ' ';
      }
    }
  }
  $cases = '';
  foreach ($final as $k => $v) {
    $cases .= '`' . $k . '` = (CASE ' . implode("\n", $v) . "\n"
      . 'ELSE `' . $k . '` END), ';
  }
  $full_table     =  $model->getConnection()->getTablePrefix() . $model->getTable();
  $query = "UPDATE `" .$full_table . "` SET " . substr($cases, 0, -2) . " WHERE `$index` IN(" . '"' . implode('","', $ids) . '"' . ");";
  \DB::update($query);
  #return $this->db->connection($this->getConnectionName($table))->update($query);
}

The test code is as follows


$userInstance = new User();
$value = [
  [
    'id' => 2,
    'contest_name' => 'A1',
    'project_name' => 'P1'
  ] ,
  [
    'id' => 3,
    'contest_name' => 'A2',
    'project_name' => 'P2'
  ] ,
];
$index = 'id';
Utils::batchUpdate($userInstance, $value, $index);

Go to work quickly after recording....

More readers interested in Laravel can check the topics of this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

Hope that this article is based on the framework of Laravel PHP programming help.


Related articles: