Skip to content

Commit 513f9fc

Browse files
authored
Merge pull request #7806 from kenjis/fix-model-cast-pk
fix: Model inserts cast $primaryKey value when using Entity
2 parents 6815f3f + a884465 commit 513f9fc

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

deptrac.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ parameters:
189189
- I18n
190190
Model:
191191
- Database
192+
- Entity
192193
- I18n
193194
- Pager
194195
- Validation

system/Model.php

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use CodeIgniter\Database\Exceptions\DatabaseException;
2121
use CodeIgniter\Database\Exceptions\DataException;
2222
use CodeIgniter\Database\Query;
23+
use CodeIgniter\Entity\Entity;
2324
use CodeIgniter\Exceptions\ModelException;
2425
use CodeIgniter\I18n\Time;
2526
use CodeIgniter\Validation\ValidationInterface;
@@ -774,11 +775,11 @@ public function update($id = null, $data = null): bool
774775
}
775776

776777
/**
777-
* Takes a class an returns an array of it's public and protected
778+
* Takes a class and returns an array of its public and protected
778779
* properties as an array with raw values.
779780
*
780781
* @param object|string $data
781-
* @param bool $recursive If true, inner entities will be casted as array as well
782+
* @param bool $recursive If true, inner entities will be cast as array as well
782783
*
783784
* @return array|null Array
784785
*
@@ -788,17 +789,32 @@ protected function objectToRawArray($data, bool $onlyChanged = true, bool $recur
788789
{
789790
$properties = parent::objectToRawArray($data, $onlyChanged);
790791

792+
$primaryKey = null;
793+
794+
if ($data instanceof Entity) {
795+
$cast = $data->cast();
796+
797+
// Disable Entity casting, because raw primary key data is needed for database.
798+
$data->cast(false);
799+
800+
$primaryKey = $data->{$this->primaryKey};
801+
802+
// Restore Entity casting setting.
803+
$data->cast($cast);
804+
}
805+
791806
// Always grab the primary key otherwise updates will fail.
792807
if (
808+
// @TODO Should use `$data instanceof Entity`.
793809
method_exists($data, 'toRawArray')
794810
&& (
795811
! empty($properties)
796812
&& ! empty($this->primaryKey)
797813
&& ! in_array($this->primaryKey, $properties, true)
798-
&& ! empty($data->{$this->primaryKey})
814+
&& ! empty($primaryKey)
799815
)
800816
) {
801-
$properties[$this->primaryKey] = $data->{$this->primaryKey};
817+
$properties[$this->primaryKey] = $primaryKey;
802818
}
803819

804820
return $properties;

0 commit comments

Comments
 (0)