在 Doctrine 中寻找答案后,我的团队发现 JMS 序列化器是“问题”。它自动触发了 Doctrine Proxies 的使用。我们为 JMS Serializer 编写了一个补丁来避免延迟加载。
我们实现了自己的DoctrineProxyHandler,它不会触发 Doctrine 延迟加载机制,并将其注册到我们的 SerializationHandlers 数组中。
class DoctrineProxyHandler implements SerializationHandlerInterface {
public function serialize(VisitorInterface $visitor, $data, $type, &$handled)
{
if (($data instanceof Proxy || $data instanceof ORMProxy) && (!$data->__isInitialized__ || get_class($data) === $type)) {
$handled = true;
if (!$data->__isInitialized__) {
//don't trigger doctrine lazy loading
//$data->__load();
return null;
}
$navigator = $visitor->getNavigator();
$navigator->detachObject($data);
// pass the parent class not to load the metadata for the proxy class
return $navigator->accept($data, get_parent_class($data), $visitor);
}
return null;
}
现在我可以简单地选择我的表,加入我需要的关联——我的 JSON 将只包含我选择的数据,而不是无限深度的关联和递归 :)
$qb= $this->_em->createQueryBuilder()
->from("\Project\Entity\Personappointment", 'pa')
->select('pa', 't', 'c', 'a')
->leftjoin('pa.table', 't')
->leftjoin('pa.company', 'c')
->leftjoin('pa.appointment', 'a')
JSON将只包含
{
Personappointment: { table {fields}, company {fields}, appointment {fields}}
Personappointment: { table {fields}, company {fields}, appointment {fields}}
Personappointment: { table {fields}, company {fields}, appointment {fields}}
.
.
}