develop
sheychen 2018-06-27 19:20:45 +02:00
parent 889b946c0b
commit dea2a99329
3 changed files with 52 additions and 1 deletions

View File

@ -78,6 +78,10 @@ class Database{
return $drop;
}
public function delete(){
return new Request\Delete($this);
}
public function getLastInsertId(): int{
return $this->pdo->lastInsertId();
}

View File

@ -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
*

36
src/Request/Delete.php Normal file
View File

@ -0,0 +1,36 @@
<?php
namespace Krutush\Database\Request;
//TODO: Split in traits
//TODO: Add INTO
//TODO: Add UNION
use Krutush\Database\DatabaseException;
class Delete extends Data{
protected $table;
protected $where;
public function from(string $table, bool $add = false): Delete{
$this->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);
}
}