2020use CodeIgniter \Database \Exceptions \DatabaseException ;
2121use CodeIgniter \Database \Exceptions \DataException ;
2222use CodeIgniter \Database \Query ;
23+ use CodeIgniter \Entity \Entity ;
2324use CodeIgniter \Exceptions \ModelException ;
2425use CodeIgniter \I18n \Time ;
2526use 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