Skip to content

Bug: model->save() insert/update data #3177

Description

@fujael

Direction
When we use model->save($data) there is no insert/update if user provides a primaryKey with its value in dataset.

Describe the bug
Let's consider this object of data to insert using save()
->save({ID: 1, name: 'A name'})
If the database table already has a row exists with primary key ID the operation will work smoothly.
But if the row doesn't exist then this function is not functional at all.
I guess this is a lack of logic to check a row before insert/update. No matter if provided data has value with primary key or not.

CodeIgniter 4 version
4.0.3 stable

Affected module(s)
All model classes

Expected behavior, and steps to reproduce if appropriate
We can update the function code like that-

` public function save($data): bool {
if (empty($data))
{
return true;
}
$builder = $this->builder();

    if (is_object($data) && isset($data->{$this->primaryKey}) && $builder->getWhere([$this->primaryKey => $data->{$this->primaryKey}])->getRow())
    {
        $response = $this->update($data->{$this->primaryKey}, $data);
    }
    elseif (is_array($data) && ! empty($data[$this->primaryKey]) && $builder->getWhere([$this->primaryKey => $data[$this->primaryKey] ])->getRow())
    {
        $response = $this->update($data[$this->primaryKey], $data);
    }
    else
    {
            $response = $this->insert($data, false);
            // call insert directly if you want the ID or the record object
            if ($response !== false)
            {
                    $response = true;
            }
    }
    return $response;
}`

Context

  • OS: [Windows 10]
  • Web server [CodeIgniter development server]
  • PHP version [7.4.5]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugVerified issues on the current code behavior or pull requests that will fix them

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions