19

In my model's beforeSave method, how can I check if the save operation is going to be an INSERT or an UPDATE?

I want to add to the model data, but only if it's inserting a new row.

BadHorsie
  • 14,135
  • 30
  • 117
  • 191

3 Answers3

23

You can just check in the data if the id exists:

function beforeSave($options = array())
{
  if(empty($this->data[$this->alias]['id']))
  {
    //INSERT
  }
  else
  {
    //UPDATE
  }
}
nIcO
  • 5,001
  • 24
  • 36
2

This is how you would do in Cakephp 4 (in case someone is looking for it)

EDIT it also applies to Cakephp 3 as BadHorsie stated

public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
    if ($entity->isNew()) {
       //INSERT
    }else{
       //UPDATE
    }
}
Olovskos
  • 45
  • 5
  • 1
    [It applies to CakePHP 3 as well](https://book.cakephp.org/3/en/orm/entities.html#checking-if-an-entity-was-persisted) – BadHorsie Jan 27 '21 at 19:41
0

You can try this

public function beforeSave($options = array()) {

    if($this->id) {
        // Update
    } else {
        // Add
    }
}
Sunil kumar
  • 761
  • 5
  • 15