Skip to content

fix: Model cannot insert when $useAutoIncrement is false #6827

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions system/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,13 @@ class Model extends BaseModel
*/
protected $escape = [];

/**
* Primary Key value when inserting and useAutoIncrement is false.
*
* @var int|string|null
*/
private $tempPrimaryKeyValue;

/**
* Builder method names that should not be used in the Model.
*
Expand Down Expand Up @@ -263,6 +270,13 @@ protected function doInsert(array $data)
$escape = $this->escape;
$this->escape = [];

// If $useAutoIncrement is false, add the primary key data.
if ($this->useAutoIncrement === false && $this->tempPrimaryKeyValue !== null) {
$data[$this->primaryKey] = $this->tempPrimaryKeyValue;

$this->tempPrimaryKeyValue = null;
}

// Require non-empty primaryKey when
// not using auto-increment feature
if (! $this->useAutoIncrement && empty($data[$this->primaryKey])) {
Expand Down Expand Up @@ -661,6 +675,10 @@ public function insert($data = null, bool $returnID = true)
}
}

if ($this->useAutoIncrement === false && isset($data[$this->primaryKey])) {
$this->tempPrimaryKeyValue = $data[$this->primaryKey];
}

$this->escape = $this->tempData['escape'] ?? [];
$this->tempData = [];

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

// Always grab the primary key otherwise updates will fail.
if (
method_exists($data, 'toRawArray') && (! empty($properties) && ! empty($this->primaryKey) && ! in_array($this->primaryKey, $properties, true)
&& ! empty($data->{$this->primaryKey}))
method_exists($data, 'toRawArray')
&& (
! empty($properties)
&& ! empty($this->primaryKey)
&& ! in_array($this->primaryKey, $properties, true)
&& ! empty($data->{$this->primaryKey})
)
) {
$properties[$this->primaryKey] = $data->{$this->primaryKey};
}
Expand Down
1 change: 0 additions & 1 deletion tests/_support/Models/WithoutAutoIncrementModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ class WithoutAutoIncrementModel extends Model
protected $table = 'without_auto_increment';
protected $primaryKey = 'key';
protected $allowedFields = [
'key',
'value',
];
protected $useAutoIncrement = false;
Expand Down