add delete function into model

Этот коммит содержится в:
Igor V Belousov 2019-11-10 12:53:15 +03:00
родитель ef5ef19daa
Коммит 3e3cfb4cf0

Просмотреть файл

@ -254,7 +254,7 @@ class Model
} }
/** /**
* Save models * Save models.
* *
* @param Model[] $models * @param Model[] $models
* *
@ -303,7 +303,7 @@ class Model
} }
} }
$pairs_string = 'SET '.implode(', ', $pairs); $pairs_string = 'SET '.implode(', ', $pairs);
$query = $db->prepare($operation." `{$table_map['name']}` $pairs_string $suffix;"); $query = $db->prepare("$operation `{$table_map['name']}` $pairs_string $suffix;");
$bind_params = []; $bind_params = [];
$num = 0; $num = 0;
@ -335,6 +335,62 @@ class Model
return false; 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 * @return array
*/ */