对于相同的场景,我是这样做的:
抛出 EntityNotFoundException 的扩展 Doctrine 代理订阅者。要覆盖服务,只需添加参数:
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');
}
}
}