Skip to content

Commit ecac1ab

Browse files
authored
Merge pull request #6827 from kenjis/fix-model-useAutoIncrement-false
fix: Model cannot insert when $useAutoIncrement is false
2 parents 23c7539 + c5ed84d commit ecac1ab

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

system/Model.php

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,13 @@ class Model extends BaseModel
118118
*/
119119
protected $escape = [];
120120

121+
/**
122+
* Primary Key value when inserting and useAutoIncrement is false.
123+
*
124+
* @var int|string|null
125+
*/
126+
private $tempPrimaryKeyValue;
127+
121128
/**
122129
* Builder method names that should not be used in the Model.
123130
*
@@ -263,6 +270,13 @@ protected function doInsert(array $data)
263270
$escape = $this->escape;
264271
$this->escape = [];
265272

273+
// If $useAutoIncrement is false, add the primary key data.
274+
if ($this->useAutoIncrement === false && $this->tempPrimaryKeyValue !== null) {
275+
$data[$this->primaryKey] = $this->tempPrimaryKeyValue;
276+
277+
$this->tempPrimaryKeyValue = null;
278+
}
279+
266280
// Require non-empty primaryKey when
267281
// not using auto-increment feature
268282
if (! $this->useAutoIncrement && empty($data[$this->primaryKey])) {
@@ -661,6 +675,10 @@ public function insert($data = null, bool $returnID = true)
661675
}
662676
}
663677

678+
if ($this->useAutoIncrement === false && isset($data[$this->primaryKey])) {
679+
$this->tempPrimaryKeyValue = $data[$this->primaryKey];
680+
}
681+
664682
$this->escape = $this->tempData['escape'] ?? [];
665683
$this->tempData = [];
666684

@@ -710,8 +728,13 @@ protected function objectToRawArray($data, bool $onlyChanged = true, bool $recur
710728

711729
// Always grab the primary key otherwise updates will fail.
712730
if (
713-
method_exists($data, 'toRawArray') && (! empty($properties) && ! empty($this->primaryKey) && ! in_array($this->primaryKey, $properties, true)
714-
&& ! empty($data->{$this->primaryKey}))
731+
method_exists($data, 'toRawArray')
732+
&& (
733+
! empty($properties)
734+
&& ! empty($this->primaryKey)
735+
&& ! in_array($this->primaryKey, $properties, true)
736+
&& ! empty($data->{$this->primaryKey})
737+
)
715738
) {
716739
$properties[$this->primaryKey] = $data->{$this->primaryKey};
717740
}

tests/_support/Models/WithoutAutoIncrementModel.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ class WithoutAutoIncrementModel extends Model
1818
protected $table = 'without_auto_increment';
1919
protected $primaryKey = 'key';
2020
protected $allowedFields = [
21-
'key',
2221
'value',
2322
];
2423
protected $useAutoIncrement = false;

0 commit comments

Comments
 (0)