Doctrine is the best way to check a record, then update or add

Several times I came across this scenario while working on the current project. I have to check if the record exists, if it is not needed, I have to add it if it happens, then I need to update. What is the standard way to do this with Doctrine?

I seem to be asking if a record exists using the find * method. Then, if it returns a positive result (object), I use this object to update. Otherwise (record not found) I need to create another object and save ().

For some reason, it just seems ineffective. Is there a better way, or am I just weird? :)

$user = Doctrine_Core::getTable('Model_User')->findOneByEmail(' myemail@email.com '); if (!$user) { $user = new Model_User(); $user->fromArray($values); // $values comes from form or wherever $user->save(); } else { $user->fromArray($values); $user->save(); } 
+4
source share
2 answers

It seems you are just doing it a little more thoroughly :) This is pretty "clean", I think:

 $user = Doctrine_Core::getTable('Model_User')->findOneByEmail(' myemail@email.com '); if (!$user) { $user = new Model_User(); } $user->fromArray($values); // $values comes from form or wherever $user->save(); 

You can tip your own:

 class Model_UserTable extends Doctrine_Table { ... public findOrCreateOneByEmail($email) { $user = $this->findOneByEmail($email); if (is_null($user)) { $user = new Model_User(); $user->email = $email; } return $user; } } 
+4
source

I wrote my own method in the desired sfDoctrineRecord class.

 public function saveOrUpdate(Doctrine_Connection $conn = null) { $object = Doctrine_Core::getTable('TableAlias')->find(array($this->getKey1(), $this->getKey2())); if (!is_object($object)) { $object = $this; }else{ $object->setVar1($this->getVar1()); $object->setVar2($this->getVar2()); $object->setVar3($this->getVar3()); $object->setVar4($this->getVar4()); } $object->save(); } 
+1
source

Source: https://habr.com/ru/post/1312593/


All Articles