From cbd59c217f3bc4a701afa38419d8a28e1367b070 Mon Sep 17 00:00:00 2001 From: kj Date: Sat, 24 Oct 2020 04:47:39 -0400 Subject: [PATCH] Added setNull method to ModelMysql. --- src/Libs/ModelMySQL.php | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Libs/ModelMySQL.php b/src/Libs/ModelMySQL.php index abb6036..adcbdbc 100644 --- a/src/Libs/ModelMySQL.php +++ b/src/Libs/ModelMySQL.php @@ -17,6 +17,7 @@ use Libs\Database; class ModelMySQL { public $id; + protected $toNull = []; static protected $primaryKey = 'id'; static protected $ignoreSave = ['id']; @@ -225,7 +226,13 @@ class ModelMySQL { foreach ($atts as $key => $value) { if (isset($value)) { $value = static::db()->real_escape_string($value); - $set[]="$key='$value'"; + if (in_array($key, $this->toNull)) + $set[]="$key=NULL"; + else + $set[]="$key='$value'"; + } else { + if (in_array($key, $this->toNull)) + $set[]="$key=NULL"; } } @@ -712,5 +719,23 @@ class ModelMySQL { return $instances; } + + /* + * Permite definir como nulo el valor de un atributo. + * Sólo funciona para actualizar un elemento de la BD, no para insertar. + * + * @param array $atts + */ + public function setNull($atts) { + if (!isset($this->id)) + throw new \Exception( + "\nEl método setNull sólo funciona para actualizar, no al insertar." + ); + + foreach ($atts as $att) { + if (!in_array($att, $this->toNull)) + $this->toNull[] = $att; + } + } } ?>