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.
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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With