Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thibaut-decherit/a77d060192c739d08973ba77bc9407ab to your computer and use it in GitHub Desktop.
Save thibaut-decherit/a77d060192c739d08973ba77bc9407ab to your computer and use it in GitHub Desktop.
Symfony Increment Database Field Properly

Symfony - Increment Database Field Properly

You must do this at the database level, not at the PHP/ORM level or it could result in a race condition.

See https://stackoverflow.com/questions/24681613/doctrine-entity-increase-value-download-counter#comment95515263_24681957

src/Repository/ExampleRepository.php:

<?php

namespace App\Repository;

use App\Entity\Example;
use Doctrine\ORM\EntityRepository;

/**
 * Class ExampleRepository
 * @package App\Repository
 */
class ExampleRepository extends EntityRepository {
    // [...]

    /**
     * @param Example $entity
     */
    public function incrementCount(Example $entity): void
    {
        $this
            ->createQueryBuilder('e')
            ->update()
            ->set('e.count', 'e.count + 1')
            ->where('e.id = :id')
            ->setParameter('id', $entity->getId())
            ->getQuery()
            ->execute();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment