public function update($fieldValues)
{
$it = $this->getIterator();
$pk = $it->getPrimaryKey();
if (empty($pk)) {
throw new ModelException(sprintf("Primary key has not been defined with @Id tag for %s", get_class($this)));
}
$stmtFields = $stmtWhere = '';
$arguments = $argumentsPk = [];
foreach ($pk as $name) {
$field = $it->getField($name);
if (!isset($this->{$name})) {
throw new ModelException(sprintf('Field "%s" is not initialized inside the %s.', $name, get_class($this)));
} else {
$stmtWhere .= ' AND ' . $field->getColumnName() . ' = ' . $field->type->wh();
$argumentsPk[] = $field->type->toDb($this->{$name});
}
}
if ($stmtWhere != '') {
$stmtWhere = substr($stmtWhere, 5);
}
foreach ($fieldValues as $fieldName => $value) {
if (is_numeric($fieldName)) {
$fieldName = $value;
$itselfValue = true;
} else {
$itselfValue = false;
}
$field = $it->getField($fieldName);
if ($field === null) {
throw new ModelException(sprintf('Field "%s" does not exist in %s.', $fieldName, get_class($this)));
}
if (isset($field->id)) {
if (!$itselfValue && $value != $this->{$fieldName}) {
throw new ModelException(sprintf('It is forbidden to change PK value from the update() method. ' . 'Field "%s" of the %s is the part of the Primary Key.', $fieldName, get_class($this)));
}
continue;
}
if (!$itselfValue) {
$this->{$fieldName} = $value;
}
if (!isset($this->{$fieldName}) && $field->column->nullable) {
$stmtFields .= ', ' . $field->getColumnName() . ' = NULL';
} else {
$stmtFields .= ', ' . $field->getColumnName() . ' = ' . $field->type->wh();
$arguments[] = $field->type->toDb($this->{$fieldName});
}
}
if (!empty($stmtFields)) {
$stmtFields = substr($stmtFields, 2);
//Saves record making insert or update
$this->db()->Execute("UPDATE " . $this->table() . " " . "SET " . $stmtFields . " " . "WHERE " . $stmtWhere . " LIMIT 1", array_merge($arguments, $argumentsPk));
}
}