1
0
mirror of https://github.com/processwire/processwire.git synced 2025-08-13 18:24:57 +02:00

DB query updates in WireSaveableItems class

This commit is contained in:
Ryan Cramer
2020-07-10 12:46:55 -04:00
parent 6f4c21d5b9
commit 0cc2bf4b79
2 changed files with 25 additions and 11 deletions

View File

@@ -232,25 +232,27 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate {
public function ___save(Saveable $item) {
$blank = $this->makeBlankItem();
if(!$item instanceof $blank) throw new WireException("WireSaveableItems::save(item) requires item to be of type '" . $blank->className() . "'");
$database = $this->wire('database');
if(!$item instanceof $blank) {
$className = $blank->className();
throw new WireException("WireSaveableItems::save(item) requires item to be of type: $className");
}
$database = $this->wire()->database;
$table = $database->escapeTable($this->getTable());
$sql = "`$table` SET ";
$id = (int) $item->id;
$this->saveReady($item);
$data = $item->getTableData();
$binds = array();
foreach($data as $key => $value) {
if(!$this->saveItemKey($key)) continue;
if($key == 'data') {
if(is_array($value)) {
$value = $this->encodeData($value);
} else $value = '';
}
if($key === 'data') $value = is_array($value) ? $this->encodeData($value) : '';
$key = $database->escapeTableCol($key);
$value = $database->escapeStr("$value");
$sql .= "`$key`='$value', ";
$bindKey = $database->escapeCol($key);
$binds[":$bindKey"] = $value;
$sql .= "`$key`=:$bindKey, ";
}
$sql = rtrim($sql, ", ");
@@ -258,15 +260,21 @@ abstract class WireSaveableItems extends Wire implements \IteratorAggregate {
if($id) {
$query = $database->prepare("UPDATE $sql WHERE id=:id");
foreach($binds as $key => $value) {
$query->bindValue($key, $value);
}
$query->bindValue(":id", $id, \PDO::PARAM_INT);
$result = $query->execute();
} else {
$query = $database->prepare("INSERT INTO $sql");
foreach($binds as $key => $value) {
$query->bindValue($key, $value);
}
$result = $query->execute();
if($result) {
$item->id = $database->lastInsertId();
$item->id = (int) $database->lastInsertId();
$this->getAll()->add($item);
$this->added($item);
}

View File

@@ -101,6 +101,9 @@ abstract class WireSaveableItemsLookup extends WireSaveableItems {
*
* Template method used by ___save()
*
* @param string $key
* @return bool
*
*/
protected function saveItemKey($key) {
if($key == $this->getLookupField()) return false;
@@ -117,7 +120,10 @@ abstract class WireSaveableItemsLookup extends WireSaveableItems {
*/
public function ___save(Saveable $item) {
if(!$item instanceof HasLookupItems) throw new WireException($this->className() . "::save() requires an item that implements HasLookupItems interface");
if(!$item instanceof HasLookupItems) {
$class = $this->className();
throw new WireException("$class::save() requires an item that implements HasLookupItems interface");
}
$database = $this->wire('database');
$lookupTable = $database->escapeTable($this->getLookupTable());