Skip to content

Commit

Permalink
Table: added createOrUpdate()
Browse files Browse the repository at this point in the history
  • Loading branch information
fabik committed Oct 16, 2012
1 parent 1e88784 commit d23bc23
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Database/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,46 @@ public function create($values)



/**
* Creates and inserts a row to the database or updates an existing one.
* @param mixed[]
* @param mixed[]
* @return ActiveRow
*/
public function createOrUpdate($uniqueKeys, $values = array())
{
if ($values) {
if ($row = $this->findOneBy($uniqueKeys)) {
$row->update($values);
return $this->findOneBy($uniqueKeys);
} else {
return $this->create($uniqueKeys + $values);
}

} else {
$connection = $this->manager->getConnection();
$driver = $connection->getSupplementalDriver();

$pairs = array();
foreach ($uniqueKeys as $key => $value) {
$pairs[] = $driver->delimite($key) . ' = ?';
}

$table = $driver->delimite($this->name);
$pairs = implode(', ', $pairs);
$values = array_values($uniqueKeys);

$connection->queryArgs(
"INSERT INTO $table SET $pairs ON DUPLICATE KEY UPDATE $pairs",
array_merge($values, $values)
);

return $this->findOneBy($uniqueKeys);
}
}



/**
* Inserts a row to the database.
* @param mixed[]
Expand Down

0 comments on commit d23bc23

Please sign in to comment.