Created
May 11, 2017 11:47
-
-
Save MartkCz/1f4166a87ec9f5ed97dd6572dc5bddcd to your computer and use it in GitHub Desktop.
Doctrine multiple insert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use Doctrine\DBAL\Connection; | |
class MultipleInsert { | |
/** @var Connection */ | |
private $connection; | |
/** @var array */ | |
private $inserts = []; | |
/** @var array */ | |
private $values = []; | |
/** @var array */ | |
private $types = []; | |
public function __construct(Connection $connection) { | |
$this->connection = $connection; | |
} | |
public function addInsert(string $tableName, array $data, array $types = []) { | |
if (empty($data)) { | |
$this->inserts[$tableName][] = []; | |
} | |
$this->inserts[$tableName][] = [ | |
implode(', ', array_keys($data)), | |
implode(', ', array_fill(0, count($data), '?')) | |
]; | |
foreach ($data as $key => $value) { | |
$this->values[] = $value; | |
$this->types[] = isset($types[$key]) ? $types[$key] : \PDO::PARAM_STR; | |
} | |
} | |
public function execute() { | |
$sql = ''; | |
foreach ($this->inserts as $tableName => $records) { | |
foreach ($records as $array) { | |
if (!$array) { | |
$sql .= "INSERT INTO {$tableName} () VALUES();\n"; | |
} else { | |
$sql .= "INSERT INTO {$tableName} ({$array[0]}) VALUES ({$array[1]});\n"; | |
} | |
} | |
} | |
$this->connection->executeUpdate($sql, $this->values, $this->types); | |
$this->inserts = []; | |
$this->values = []; | |
$this->types = []; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment