Symfony2 SoftDeleteable无法使用QueryBuilder删除

时间:2013-07-15 14:41:50

标签: php symfony doctrine-orm soft-delete

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

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

如何通过实体管理器或查询构建器

在所有情况下允许软删除

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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的方式更专业,更符合标准。