Symfony2 SoftDeleteable not working on QueryBuilder Delete

The behavior of Softdelete works fine when executing the delete statement using the entity manager in the form of the following code:

$entity = $this->em->getRepository('Users')->find(7); $this->em->remove($entity); $this->em->flush(); 

but when performing the same function using QueryBuilder, hard deletion will be performed in the database

 $qb = $this->em->createQueryBuilder(); $qb->delete('Users', 'p'); $qb->where($qb->expr()->eq('p.id', ':id')); $qb->setParameters(array("id" => 7)); $result = $qb->getQuery()->getResult(); 

How can I enable softdelete in all cases, either through the entity manager or query builder

+4
source share
2 answers

If you are using DQL, you need to use the query hint. This should do the trick:

 $query = $qb->getQuery() $query->setHint( \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\SoftDeleteable\Query\TreeWalker\SoftDeleteableWalker' ); $result = $query->getResult(); 

Update:

The docs mention that you should use a query hint, but don't give an example, so I pulled it out of my tests.

Docs: https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/softdeleteable.md

Test Usage: https://github.com/l3pp4rd/DoctrineExtensions/blob/master/tests/Gedmo/SoftDeleteable/SoftDeleteableEntityTest.php

+11
source

my old solution after the previous answer from @Ken Hannel:

Edit: /vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php

Replace the walkDeleteClause function as follows:

  public function walkDeleteClause(AST\DeleteClause $deleteClause) { $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName); $tableName = $class->getTableName(); $sql = 'DELETE FROM ' . $this->quoteStrategy->getTableName($class, $this->platform); $this->setSQLTableAlias($tableName, $tableName, $deleteClause->aliasIdentificationVariable); $this->rootAliases[] = $deleteClause->aliasIdentificationVariable; //check if SoftDeleteableListener is attached foreach ($this->em->getEventManager()->getListeners() as $eventName => $listeners) { foreach ($listeners as $listener) { if ($listener instanceof \Gedmo\SoftDeleteable\SoftDeleteableListener) { $date = date('Ymd H:i:s'); $sql = 'UPDATE ' . $this->quoteStrategy->getTableName($class, $this->platform) . " SET deletedAt = ' " . $date . " ' "; } } } return $sql; } 

but actually, but I think Ken Hannel’s method is more professional and conforms to the standard.

0
source

Source: https://habr.com/ru/post/1491453/


All Articles