diff --git a/src/Database.php b/src/Database.php index bd16445..bf2c6d8 100644 --- a/src/Database.php +++ b/src/Database.php @@ -78,6 +78,10 @@ class Database{ return $drop; } + public function delete(){ + return new Request\Delete($this); + } + public function getLastInsertId(): int{ return $this->pdo->lastInsertId(); } diff --git a/src/Model.php b/src/Model.php index 86c1150..7f30cdf 100644 --- a/src/Model.php +++ b/src/Model.php @@ -176,7 +176,7 @@ class Model{ throw new DatabaseException('Can\'t find class '.$model.' for foreign in field '.$field); $id = $this->{isset($foreign['for']) ? $foreign['for'] : $field}; - $where = $model::getColumn(isset($foreign['field']) ? $foreign['field'] : $model::ID).' = ?'; + $where = '`'.$model::getColumn(isset($foreign['field']) ? $foreign['field'] : $model::ID).'` = ?'; $value = (isset($foreign['multiple']) && $foreign['multiple']) ? $model::all([$id], $where): @@ -596,6 +596,17 @@ class Model{ return $this; } + /** + * Delete instance in database + */ + public function runDelete(){ + $req = Connection::get(static::DATABASE) + ->delete() + ->from(static::TABLE) + ->where(implode(' AND ', array_map(function($field){ return $field.' = ?'; }, static::getPrimaryColumns()))) + ->run($this->getPrimaryValues()); + } + /** * Create Request\Create from Model * diff --git a/src/Request/Delete.php b/src/Request/Delete.php new file mode 100644 index 0000000..af7670d --- /dev/null +++ b/src/Request/Delete.php @@ -0,0 +1,36 @@ +table = ($add && $this->table ? $this->table.', ' : '').$table; + return $this; + } + + public function where(string $where, bool $add = false): Delete{ + $this->where = $add && $this->where ? '('.$this->where.') AND ('.$where.')' : $where; + return $this; + } + + public function sql(){ + if(!isset($this->table)) + throw new DatabaseException('Any table set'); + + $sql = 'DELETE FROM '.$this->table. + ($this->where ? ("\n".'WHERE '.$this->where) : ''); + return $sql; + } + + public function run(array $values = null){ + return parent::execute($this->sql(), $values); + } +} \ No newline at end of file