views:

1330

answers:

2

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 subqueries, 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?

+3  A: 

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

pix0r
the only problem with REPLACE seems to be that it drops and then creates a new row (rather than performing an actual UPDATE), thus dropping the auto increment ids (in this case, my primary id). Am I missing something here?eg - my auto increment id is 9, but the count is as 3000. When I perform REPLACE INTO for row 9, the new row id is 3001.
sean smith
+1  A: 

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();
ken
There's nothing that ensures that the row isn't created between the query and the save.
Ilia Jerebtsov
I would usually do another find before the save statement but Doctrine uses query caching so it will still return the entity.
ken