Updating Entities When an Insert Has a Duplicate Key in Doctrine ORM

There may be times when Doctrine may or may not know if an entity already exists in your database. Doctrine ORM provides a handy way to merge an entity to the database, meaning that it will insert any new entities, and update any existing ones.

Most PHP developers come from a MySQL background, where you can simply use ‘ON DUPLICATE KEY’ to achieve this:

INSERT INTO table (id, value) values('test', 'TEST') ON DUPLICATE KEY UPDATE value = values(name)

Unfortunately, because Doctrine is database agnostic, this will not work when using DQL. Instead, Doctrine ORM provides a handy way of achieving this within the ORM:

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

// If an entity with ID 1 already exists, this will update it, otherwise it will insert it
$entityManager->merge($entity);
$entityManager->flush();

Article written by:

Lewis

Lewis has sneakily turned an unhealthy compulsion for efficiency into a successful business, and has vowed to continue to push the boundary in other obsessions he can pass off as "work".

You might also like...

Handling Authentication when Using Behat & Mink

We use a combination of Behat, Mink and Sauce to make sure all of our applications are automatically and continually rested. If you’ve ever suffered from ‘deployment dread’ (the feeling of fear that occurs for a few hours after deploying your code), it’s probably because you don’t have confidence in your automated testing - or worse - you don’t have any. We’ve tried a number of tools and processes to reduce our deployments dread, but none have cured our fear as much as Behat.

Read more about Handling Authentication when Using Behat & Mink

Docker for Mac Performance using NFS (Updated for macOS Catalina)

We heavily use Docker for Mac for the internal development of our products. It allows us to closely replicate the internal, automated testing, user acceptance testing and production platforms. There is just one problem, that I'm sure you've also found... The performance of the file system when using volume mounts.

Read more about Docker for Mac Performance using NFS (Updated for macOS Catalina)

Ansible and Let's Encrypt for Multi-Tenancy Applications

We needed SSL certificates for a multi-tenanted app (single app that loads different configuration based on the tenant that accesses it) that relied on domain based tenant location (done via CNAME as the domains were different per tenant). It also had to be easily configurable so that adding a new tenant didn't require major work to get them up and running.

Read more about Ansible and Let's Encrypt for Multi-Tenancy Applications