我正在使用来自 Doctrine 查询的实体对象,最终得到一个非常大的数组,来自所有实体的所有信息都相关。这最终成为一个巨大的数据树...我怎样才能限制这种情况?避免列出所有关系中的所有数据?
您始终可以删除不需要的关联(这是加速 Doctrine 的最佳实践)。或者,您可以仅选择表示层中所需的字段(作为只读数据):
public function getAll()
{
$qb = $this->createQueryBuilder('u'); // Where are in User custom repository
return $qb
->select(array('u.id', 'u.first', 'u.last'))
->getQuery()
->getResult();
}
如果您仍然需要使用对象(或对于需要纯SQL的复杂查询),则可能仅填充域对象的所需属性(最终填充关联/嵌套集合)。
例如,有关本机SQL的更多信息:
public function getAll()
{
$mapping = new DoctrineORMQueryResultSetMapping();
$mapping->addEntityResult('AcmeHelloBundleUser', 'e');
$mapping->addFieldResult('e', 'id', 'id');
$mapping->addFieldResult('e', 'first', 'first');
$mapping->addFieldResult('e', 'last', 'last');
$sql = "SELECT id, first, last FROM user ";
$result = $this->_em->createNativeQuery($sql, $mapping)->getResult();
// Or hust return $result itself (array)
return new DoctrineCommonCollectionsArrayCollection($result);
}
当然,缺点(?)是使用本机SQL。我不相信ResultSetMapping
可以与 DQL 一起使用。
编辑:看看 http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/best-practices.html