5

Softdelete 行为在通过实体管理器执行删除语句时正常工作,如下代码:

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

但是当通过 QueryBuilder 执行相同的功能时,硬删除将在数据库上执行

$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();

如何在所有情况下通过实体管理器或查询生成器允许软删除

4

2 回答 2

11

如果您使用 DQL,那么您必须使用查询提示。这应该可以解决问题:

$query = $qb->getQuery()

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

$result = $query->getResult();

更新:

文档提到您必须使用查询提示但没有提供示例,因此我从他们的测试中提取了用法。

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

测试用法:https ://github.com/l3pp4rd/DoctrineExtensions/blob/master/tests/Gedmo/SoftDeleteable/SoftDeleteableEntityTest.php

于 2013-07-16T19:47:22.800 回答
0

在@Ken Hannel 之前的回答之后,我的旧解决方案是:

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

替换 walkDeleteClause 函数如下:

 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('Y-m-d H:i:s');
                $sql = 'UPDATE ' . $this->quoteStrategy->getTableName($class, $this->platform) . " SET deletedAt = ' " . $date . " ' ";
                }
            }
        }
        return $sql;
    }

但实际上,但我认为 Ken Hannel 的方式更专业,更符合标准。

于 2013-07-29T15:55:55.873 回答