diff --git a/src/core/Model.php b/src/core/Model.php index e6221a5..798b0aa 100644 --- a/src/core/Model.php +++ b/src/core/Model.php @@ -254,7 +254,7 @@ class Model } /** - * Save models + * Save models. * * @param Model[] $models * @@ -302,22 +302,22 @@ class Model $pairs[] = "`{$column_name}` = :param_{$param_name}"; } } - $pairs_string = 'SET ' . implode(', ', $pairs); - $query = $db->prepare($operation." `{$table_map['name']}` $pairs_string $suffix;"); + $pairs_string = 'SET '.implode(', ', $pairs); + $query = $db->prepare("$operation `{$table_map['name']}` $pairs_string $suffix;"); $bind_params = []; $num = 0; foreach ($data_model as $item => $value) { if ($table_map['id'] !== $item) { $bind_params[$num] = $value; - $query->bindParam(':param_' . $item, + $query->bindParam(':param_'.$item, $bind_params[$num]); ++$num; } } if ($update_mode) { $bind_params[$num] = $data_model[$table_map['id']]; - $query->bindParam(':param_' . $table_map['id'], + $query->bindParam(':param_'.$table_map['id'], $bind_params[$num]); } @@ -335,6 +335,62 @@ class Model return false; } + /** + * Remove model data from a table and unset them. + * + * @param Model[] $models + * + * @return bool + * + * @throws Exception + */ + public static function delete(array &$models): bool + { + if (count($models)) { + if ($models[0] instanceof Model) { + if ('db' !== $models[0]->getModelType()) { + throw new Exception('Item 0 is not Model of a db type'); + } + + $db = $models[0]->app->db; + $db->beginTransaction(); + + foreach ($models as $number => $model) { + if ($model instanceof Model) { + if ('db' !== $model->getModelType()) { + $db->rollBack(); + throw new Exception("Item $number is not Model of a db type"); + } + $table_map = $model->getInternalTableMap(); + + $id = null; + (function () use (&$id, $table_map) { + $id = $this->{$table_map['id']}; + })->call($model); + + $query = $db->prepare("DELETE FROM `{$table_map['name']}` WHERE `{$table_map['fields'][$table_map['id']]}` = :param_{$table_map['id']}"); + + $query->bindParam(':param_'.$table_map['id'], $id); + if (!$query->execute()) { + $db->rollBack(); + throw new Exception("Item $number not deleted"); + } + } + } + + $db->commit(); + + foreach ($models as $key => $model) { + unset($models[$key]); + } + + return true; + } + } + + return false; + } + /** * @return array */