sur update, ne faire l'update que sur les colonnes dont on a affectée une valeur depuis le chargement de l'objet

This commit is contained in:
Gregory Letellier
2023-10-27 09:23:08 +02:00
parent a2dc633be4
commit a7d63c8c07

View File

@@ -5,6 +5,7 @@ namespace Kletellier\PdoWrapper;
class Model class Model
{ {
protected mixed $values; protected mixed $values;
protected array $updated;
protected string $table; protected string $table;
protected string $pk; protected string $pk;
private Db $db; private Db $db;
@@ -15,6 +16,7 @@ class Model
$this->db = Db::getInstance(); $this->db = Db::getInstance();
$this->new = true; $this->new = true;
$this->values = array(); $this->values = array();
$this->updated = array();
$this->pk = "id"; $this->pk = "id";
$this->table = $this->getDefaultTableName(); $this->table = $this->getDefaultTableName();
} }
@@ -45,6 +47,7 @@ class Model
{ {
$this->values = $data; $this->values = $data;
$this->new = false; $this->new = false;
$this->updated = [];
return $this; return $this;
} }
@@ -61,8 +64,18 @@ class Model
$ret = true; $ret = true;
} }
} else { } else {
$query = $qb->getPreparedQuery($this->values, false); if (count($this->updated) > 0) {
$data = [];
$data[$this->pk] = $this->values[$this->pk];
foreach ($this->updated as $updatecol) {
$data[$updatecol] = $this->values[$updatecol];
}
$query = $qb->getPreparedQuery($data, false);
$ret = $this->db->updateQuery($query); $ret = $this->db->updateQuery($query);
if ($ret) {
$this->updated = [];
}
}
} }
return $ret; return $ret;
} }
@@ -75,6 +88,9 @@ class Model
public function __set($name, $value): void public function __set($name, $value): void
{ {
$this->values[$name] = $value; $this->values[$name] = $value;
if (!$this->new && !in_array($name, $this->updated)) {
$this->updated[] = $name;
}
} }
public function __get($name): mixed public function __get($name): mixed