0

我正在处理来自 Doctrine 查询的实体对象,我最终得到了一个非常大的数组,其中包含来自所有相关实体的所有信息。这最终成为一个巨大的数据树......我该如何限制呢?避免列出所有关系中的所有数据?

4

1 回答 1

1

你总是可以删除不需要的关联(这是加速 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 \Doctrine\ORM\Query\ResultSetMapping();

    $mapping->addEntityResult('Acme\HelloBundle\User', '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 \Doctrine\Common\Collections\ArrayCollection($result);
}

当然,缺点(?)是使用本机 SQL。我不相信它ResultSetMapping可以与 DQL 一起使用。

编辑:看看http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/best-practices.html

于 2012-08-08T22:54:58.423 回答