I am trying to update a record in mysql. My code sniplet is as follows;
if ($this->model->save($update_post))
{ }
Currently, this query doesn't update but add a new record with insert. What is the governing factor to update, rather than insert please? Alternatively, should I force update instead of using save?
Any pointers much appreciated.
save()
method in Codeigniter 4, first look at the data that you passed inside it. If it contains the primary key then it updates the existing record else it inserts it into the database.
In your case, $update_post
,
If $update_post
has a primary key attribute, then it updates to that record.
Example:
If we have table 'POST' with column 'ID', 'name' etc.
So inside Model class:
$post = $this->where('id',1)->first();
$post->name = 'Updated Name';
$this->save($post);
Another reason may be you have a different primary key rather than 'id', in this case, you must specify this primary key in your model class.
$protected primaryKey = 'any_other_key';