Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing "update if exists" in Doctrine ORM

I am trying to INSERT OR UPDATE IF EXISTS in one transaction.

in mysql, I would generally use DUPLICATE KEY ("UPDATE ON DUPLICATE KEY".) I'm aware of many solutions to this problem using various SQL variants and sub-queries, but I'm trying to implement this in Doctrine (PHP ORM). It seems there would be Doctrine methods for doing this since it's so feature packed, but I'm not finding anything. Is this sort of thing a problem using PHP ORM packages for some reason? Or do any Doctrine experts know how to achieve this through hacks or any means?

like image 956
seans Avatar asked Jul 15 '09 16:07

seans


3 Answers

According to https://www.vivait.co.uk/labs/updating-entities-when-an-insert-has-a-duplicate-key-in-doctrine this can be achieved with $entityManager->merge().

$entity = new Table();
$entity->setId(1);
$entity->setValue('TEST');

$entityManager->merge($entity);
$entityManager->flush();
like image 136
Björn Tantau Avatar answered Nov 20 '22 04:11

Björn Tantau


The only thing I can think of is to query first for the entity if it exists otherwise create new entity.

if(!$entity = Doctrine::getTable('Foo')->find(/*[insert id]*/))
{
   $entity = new Foo();
}
/*do logic here*/
$entity->save();
like image 43
ken Avatar answered Nov 20 '22 05:11

ken


Doctrine supports REPLACE INTO using the replace() method. This should work exactly like the ON DUPLICATE KEY UPDATE you were looking for.

Docs: Replacing Records

like image 3
pix0r Avatar answered Nov 20 '22 03:11

pix0r