diff --git a/deptrac.yaml b/deptrac.yaml index d2db0605103b..271378bfde55 100644 --- a/deptrac.yaml +++ b/deptrac.yaml @@ -189,6 +189,7 @@ parameters: - I18n Model: - Database + - Entity - I18n - Pager - Validation diff --git a/system/Model.php b/system/Model.php index dc49f398c28d..25b2b354b990 100644 --- a/system/Model.php +++ b/system/Model.php @@ -20,6 +20,7 @@ use CodeIgniter\Database\Exceptions\DatabaseException; use CodeIgniter\Database\Exceptions\DataException; use CodeIgniter\Database\Query; +use CodeIgniter\Entity\Entity; use CodeIgniter\Exceptions\ModelException; use CodeIgniter\I18n\Time; use CodeIgniter\Validation\ValidationInterface; @@ -774,11 +775,11 @@ public function update($id = null, $data = null): bool } /** - * Takes a class an returns an array of it's public and protected + * Takes a class and returns an array of its public and protected * properties as an array with raw values. * * @param object|string $data - * @param bool $recursive If true, inner entities will be casted as array as well + * @param bool $recursive If true, inner entities will be cast as array as well * * @return array|null Array * @@ -788,17 +789,32 @@ protected function objectToRawArray($data, bool $onlyChanged = true, bool $recur { $properties = parent::objectToRawArray($data, $onlyChanged); + $primaryKey = null; + + if ($data instanceof Entity) { + $cast = $data->cast(); + + // Disable Entity casting, because raw primary key data is needed for database. + $data->cast(false); + + $primaryKey = $data->{$this->primaryKey}; + + // Restore Entity casting setting. + $data->cast($cast); + } + // Always grab the primary key otherwise updates will fail. if ( + // @TODO Should use `$data instanceof Entity`. method_exists($data, 'toRawArray') && ( ! empty($properties) && ! empty($this->primaryKey) && ! in_array($this->primaryKey, $properties, true) - && ! empty($data->{$this->primaryKey}) + && ! empty($primaryKey) ) ) { - $properties[$this->primaryKey] = $data->{$this->primaryKey}; + $properties[$this->primaryKey] = $primaryKey; } return $properties;