diff --git a/src/Libs/Model.php b/src/Libs/Model.php index 158bedd..0161e0f 100644 --- a/src/Libs/Model.php +++ b/src/Libs/Model.php @@ -43,6 +43,10 @@ class Model */ protected static array $dbForceSave = []; + /** + * @var bool Attribute that persis if is current model is saved into the database + */ + protected bool $dbIsSaved = false; /** * @var string The database table name. @@ -306,6 +310,8 @@ class Model } } + $instance->markAsSaved(); + return $instance; } @@ -466,23 +472,34 @@ class Model $pk = static::$dbPrimaryKey; $this->$pk = $db->lastInsertId(); + $this->markAsSaved(); } /** * Checks if the object to be saved is new or not, and based on the result, * calls `update` to update an existing row or `add` to insert a new row. + * * @return void */ public function save(): void { - $pk = static::$dbPrimaryKey; - if (isset($this->$pk)) { + if ($this->dbIsSaved) { $this->update(); } else { $this->add(); } } + /** + * Mark the current instance as already saved + * + * @return void + */ + public function markAsSaved(): void + { + $this->dbIsSaved = true; + } + /** * Deletes the current object from the database. * @return void @@ -495,6 +512,7 @@ class Model static::$dbQueryVariables[":$pk"] = $this->$pk; static::query($sql); + $this->dbIsSaved = false; } /**