Skip to content

Instantly share code, notes, and snippets.

@artyuum
Last active September 30, 2020 19:14
Show Gist options
  • Save artyuum/98144d74f5a55a45cfa1544f6fb013bf to your computer and use it in GitHub Desktop.
Save artyuum/98144d74f5a55a45cfa1544f6fb013bf to your computer and use it in GitHub Desktop.
Doctrine deleteBy() criteria
<?php
class TokenRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Token::class);
}
public function deleteBy(array $criteria)
{
$query = $this->createQueryBuilder('t')->delete();
foreach ($criteria as $property => $value) {
$query
->andWhere('t.' . $property . ' = :' . $property)
->setParameter($property, $value)
;
}
return $query
->getQuery()
->execute()
;
}
}
@artyuum
Copy link
Author

artyuum commented Sep 30, 2020

This is how I implemented a findBy()-like method for the delete action in my token repository. It can be used in other repositories as well, you just need to change the alias used in the DQL.

Usage

$tokenRepository->deleteBy([
    'user' => $user,
    'type' => Token::RESET_PASSWORD_TYPE
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment