Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doctrine save method update/insert based on unique field

Tags:

php

doctrine

I read so many post and I found many variations about how to get save to insert vs update but couldn't find something that would work for me.

I am guessing that preSave would be the way to go if preSave() is being executed automaticly by save() if present.

columns:
  email:
    type: string(255)
    unique: true
    email: true

I need save() to check if a filed is set to be unique if so, to check if field data in this case email address is unique. Based on that info decide to insert or update posted fields that have changed.

like image 901
RoboTamer Avatar asked Jan 01 '26 04:01

RoboTamer


1 Answers

Just adding a little more logic, there could be better ways of doing it, but this works for me.

public function  preInsert($event) {
    if ($this->state() == Doctrine_Record::STATE_TDIRTY) {
            $r == findRecordInDatabaseUsingThis();
            $this->assignIdentifier($r->id);
            $this->refresh();
            $this->state(Doctrine_Record::STATE_CLEAN); // STATE_DIRTY to do an update, this will just use the existing record without updating
            $event->skipOperation();
        }
    }
}
like image 84
Peter Lindqvist Avatar answered Jan 02 '26 18:01

Peter Lindqvist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!