Welcome Guest, Not a member yet? Register   Sign In
Issues with $model->save() and duplicate primary key
#1

(This post was last modified: 04-20-2023, 07:36 AM by joho.)

Quite similar to this thread, but not identical:
https://forum.codeigniter.com/showthread.php?tid=81583

I use the $model->save() method to let it do the "magic" of choosing between update/insert. Yet, when the primary key is passed in the data array to save(), I get a duplicate key error.

Pseudo code:
PHP Code:
$save_data = [ 'name' => $person_name'city' => $person_city ];
if ( ! 
$is_new_person ) {
  $save_data['id'] = $person_id;
}
$model->save$save_data ); 


I'm obviously not doing it right, but I thought that $model->save() would see the primary key ('id') being present in the $save_data and thus do an update instead of an insert.

What's also strange is that in the validation rules, I specify that $person_name must be unique, and pass it the 'id' key, and the validation goes through OK when editing a record and just modify the $person_city (i.e. it does properly check that the record being edited is the one with the same $person_name, and thus it's not a duplicate).

Ah, yes ...

Code:
class mySpecialModel extends Model
{
    protected $primaryKey = 'id';
    ..
    ..
}

makes it work a little bit better :-)

-joho
Reply




Theme © iAndrew 2016 - Forum software by © MyBB