我在一个有很多交叉引用数据的系统中使用了Gedmo Doctrine Extension和SoftDeleteable扩展。我遇到了如下情况:
- 产品 A 被分配为供应商 B
- 供应商 B 已被 [软] 删除
- 产品 A 现在在序列化时引发"实体不存在",因为"供应商"外键仍具有供应商 B 的 ID,即使实体被软删除且无法提取。
应该注意的是,我不希望删除级联,这意味着我不想仅仅因为供应商 B 已被删除而删除产品 A。我只需要在删除供应商记录时将供应商外键设置为 NULL(或被 JMS 解释为 NULL)。
这是一个很常见的场景,我无法想象其他人没有遇到这种情况,但我找不到任何答案。有人有什么建议吗?
谢谢-内特
这是我在相同情况下所做的:
扩展原则代理订阅者,其中抛出 EntityNotFoundException。要覆盖服务,只需添加参数:
jms_serializer.doctrine_proxy_subscriber.class: YourCustom'JMSDoctrineProxySubscriber
在您的自定义 DoctrineProxySubscriber 上
<?php
namespace YourCustom;
use Doctrine'ORM'EntityNotFoundException;
use JMS'Serializer'EventDispatcher'PreSerializeEvent;
use JMS'Serializer'EventDispatcher'Subscriber'DoctrineProxySubscriber;
class JMSDoctrineProxySubscriber extends DoctrineProxySubscriber
{
public function onPreSerialize(PreSerializeEvent $event)
{
try {
parent::onPreSerialize($event);
} catch (EntityNotFoundException $e) {
// The exception is thrown when soft-deleted objects are tried to be loaded.
// Soft-deleted Doctrine proxy objects should be treated as null. Overriding event type which is eventually
// a class name to stdClass would make it skip and result in as null.
$event->setType('stdClass');
}
}
}
试试这个:
$product = $em->find('models'ProductA', 1);
$supplier = $product->getSupplier();
$product->setSupplier(null);
$em->remove($supplier);
$em->flush();