How can I write an INSERT
doctrine query with option ON DUPLICATE KEY UPDATE
?
相关问题
- php PDO::FETCH_ASSOC doesnt detect select after ba
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- MySQL: conduct a basic search
- Why sometimes there is one of more gap(s) in the v
I had the same problem and after investigating a bit it looks like Doctrine doesn't do it. My solution was to do a findBy before my insert to see if any records exist with the unique fields. If this returns an entity then I update that entity and persist it instead of creating a new entity to persist.
If you are concerned about performance then this is not ideal as we are doing a select before every insert. However since Doctrine is database agnostic it is the only alternative to locking yourself to MySQL. It's one of those tradeoffs: do you want performance or portability.
for Symfony 2 use raw sql:
You can't. It's not supported by Doctrine right now.
What you could do is to imitate what MySQL does by checking if the entity exists and update/create it accordingly:
If the record exists
PESSIMISTIC_WRITE
makes sure that it's not updated by anyone (e.g., other threads) while we're updating it.Although you need to check for the entity's existence on every update, it's a simple reproduction of "update if existing and create if not".
As pointed out in the comments this does not prevent a race condition if the record doesn't exist: If a row with the same key(s) gets inserted between the select and the insert you're running into a duplicate key exception.
But given the constraints that this needs to be DB independent and thus written using Doctrine and not using native SQL it may help in some cases.
References: