How do I check if it was an INSERT or UPDATE in Cakephp’s save method?

Asked

Viewed 312 times

1

Hello, I have a script that gets an ID by a POST notification along with other data. It turns out that the ID is from a transaction created on another system (Ids are not generated by auto_increment).

An example of data I receive would be:

{'id' : 1234, 'data' : '2014-06-02', 'etc' : 'teste'}

I create the array based on this json that I receive by POST.

$dados['Model'] = array(
   'id' => $json->id, 
   'data' => $json->data, 
   'etc' => $json->etc
);
$this->Model->save($dados);

How to know if the save() method in the controller did an update or an Insert since the id is my Primary key?

1 answer

1

As I needed in the controller I ended up putting in the model the callback afterSave() as follows.

class Model extends AppModel {

    public $sqlType = false;

    public function afterSave($created){
        if ($created){
            $this->sqlType = 'INSERT';
        } else {
            $this->sqlType = 'UPDATE';
        }
    }
}

and in the controller

$this->Model->save($dados);
if ($this->Model->sqlType == 'INSERT'){

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.