我在https://github.com/KnpLabs/DoctrineBehaviors/#softDeletable的实体中使用SoftDeletable特征它工作正常,但有时我想强行删除实体。我怎么能这样做?
当我使用<?php
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
时,它会被软删除,但我需要将其从数据库中完全删除。
答案 0 :(得分:2)
只需从EventManager
移除订阅者,然后在remove()
/ flush()
操作后重新添加订阅者。
// get the event-manager
$eventManager = $this->get('doctrine')->getEventManager();
// get the listener
$subscriber = $this->get('knp.doctrine_behaviors.softdeletable_subscriber');
// remove the the subscriber for all events
$eventManager->removeEventListener($subscriber->getSubscribedEvents(), $subscriber);
// remove the entity
$em->remove($entity);
$em->flush();
// add it back to the event-manager
$eventManager->addEventSubscriber($subscriber);
答案 1 :(得分:2)
由于nifr的答案在当前版本的行为中不再起作用,我对问题有了更深入的了解并得到了解决方案:
$em = $this->getDoctrine()->getManager();
// initiate an array for the removed listeners
$originalEventListeners = array();
// cycle through all registered event listeners
foreach ($em->getEventManager()->getListeners() as $eventName => $listeners) {
foreach ($listeners as $listener) {
if ($listener instanceof Knp\DoctrineBehaviors\ORM\SoftDeletable\SoftDeletableSubscriber) {
// store the event listener, that gets removed
$originalEventListeners[$eventName] = $listener;
// remove the SoftDeletableSubscriber event listener
$em->getEventManager()->removeEventListener($eventName, $listener);
}
}
}
// remove the entity
$em->remove($entity);
$em->flush();
// re-add the removed listener back to the event-manager
foreach ($originalEventListeners as $eventName => $listener) {
$em->getEventManager()->addEventListener($eventName, $listener);
}
答案 2 :(得分:0)
我找到了简单的解决方案。实体将首先被软删除,但如果它已经被软删除,它将被删除,所以我的简单解决方案是:
$entity->setDeletedAt(new DateTime());
$entityManager->remove($entity);
$entityManager->flush();
当然你需要禁用&#39; softdelete&#39;首先过滤并删除它是一个sofdelete字段。