Fixed Database::lastInsertId call for PostgreSQL

This commit is contained in:
Dmitry Khomutov 2017-04-16 21:18:21 +07:00
parent a671f4d81d
commit 142f05b416
No known key found for this signature in database
GPG key ID: 7EB36C9576F9ECB9
3 changed files with 24 additions and 8 deletions

View file

@ -10,6 +10,20 @@ class Database extends \PDO
protected static $details = [];
protected static $lastUsed = ['read' => null, 'write' => null];
/**
* @param string $table
*
* @return string
*/
public function lastInsertIdExtended($table = null)
{
if ($table && $this->getAttribute(self::ATTR_DRIVER_NAME) == 'pgsql') {
return parent::lastInsertId($table . '_id_seq');
}
return parent::lastInsertId();
}
protected static function init()
{
$config = Config::getInstance();

View file

@ -251,26 +251,28 @@ abstract class Store
public function saveByInsert(Model $obj, $saveAllColumns = false)
{
$rtn = null;
$data = $obj->getDataArray();
$rtn = null;
$data = $obj->getDataArray();
$modified = ($saveAllColumns) ? array_keys($data) : $obj->getModified();
$cols = [];
$values = [];
$qParams = [];
foreach ($modified as $key) {
$cols[] = $key;
$values[] = ':' . $key;
$cols[] = $key;
$values[] = ':' . $key;
$qParams[':' . $key] = $data[$key];
}
if (count($cols)) {
$qs = 'INSERT INTO {{' . $this->tableName . '}} (' . implode(', ', $cols) . ') VALUES (' . implode(', ',
$values) . ')';
$qs = 'INSERT INTO {{' . $this->tableName . '}} (' . implode(', ', $cols) . ') VALUES (' . implode(', ', $values) . ')';
$q = Database::getConnection('write')->prepareCommon($qs);
if ($q->execute($qParams)) {
$id = !empty($data[$this->primaryKey]) ? $data[$this->primaryKey] : Database::getConnection('write')->lastInsertId();
$id = !empty($data[$this->primaryKey])
? $data[$this->primaryKey]
: Database::getConnection('write')->lastInsertIdExtended($obj->getTableName());
$rtn = $this->getByPrimaryKey($id, 'write');
}
}

View file

@ -9,7 +9,7 @@
<div class="box-body">
<?= $exception->getMessage(); ?><br />
File: <?= $exception->getFile(); ?><br />
Line: <?= $exception->getLine(); ?><br />
Line: <?= $exception->getLine(); ?>
<pre>
<?= $exception->getTraceAsString(); ?>
</pre>