CakePHP - How to check in beforeSave if it's an INSERT or UPDATE
Asked Answered
I

3

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.

Impulse answered 4/12, 2012 at 12:46 Comment(0)
C
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
  }
}
Coremaker answered 4/12, 2012 at 14:33 Comment(2)
Pretty simple, I don't know why I didn't think of this... :/ Thanks!Impulse
Update: in Cake 2.3 you should check if $this->id is empty.Psalmody
H
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
    }
}
Humour answered 27/1, 2021 at 17:6 Comment(1)
It applies to CakePHP 3 as wellImpulse
T
0

You can try this

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

    if($this->id) {
        // Update
    } else {
        // Add
    }
}
Thyestes answered 24/5, 2016 at 11:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.