学说2:查询可能大量的记录

时间:2014-12-01 15:00:13

标签: php doctrine-orm doctrine

我正在为我的网站构建一个仪表板,用户可以通过所有时间,过去12个月,过去6个月和过去3个月查看数据库表中的记录数。我发现,由于可能有数千条记录和多个用户同时请求这些数据,这可能会使服务器陷入困境。

使用Doctrine 2是否有最佳方法?现在,我必须实现的功能如下:

/**
 * Search group instruction sessions based on the number of months selected from the dashboard gauges.
 *
 * @param int $number_months (how many months back to search)
 * @param User $user_obj (optional- the user being searched)
 * @return Response
 */
private function __recordsByNumberOfMonths($number_months, $user_obj = NULL){       
    $from = date('Y-m-d', strtotime('-'.$number_months.' months'));

    //get surveys by a specific user
    if($user_obj != NULL){
        $query = $this->entityManager->createQuery('SELECT i FROM GroupInstruction i WHERE i.librarian = :librarian AND i.instruction_date > :from ORDER BY i.instruction_date DESC');
        $query->setParameter('from', $from);
        $query->setParameter('librarian', $user_obj);
    } 
    //get all surveys by all users
    else {
        $query = $this->entityManager->createQuery('SELECT i FROM GroupInstruction i WHERE i.instruction_date > :from ORDER BY i.instruction_date DESC');
        $query->setParameter('from', $from);
    }
    $results = $query->getResult();

    $total_results = count($results);

    return $total_results;
}

任何关于优化的提示(或者如果我完全倒退的话)都将不胜感激!

2 个答案:

答案 0 :(得分:2)

我认为阵列水合作用比物体水合作用更快:

$query->getResult( Doctrine\ORM\Query::HYDRATE_ARRAY );

这样您就可以将数据作为基本类型的数组而不是对象数组。

答案 1 :(得分:0)

使用doctrine缓存它:) http://doctrine-orm.readthedocs.org/en/latest/reference/caching.html 其次,如果您不想获取数据,请准备计数对象的查询 - 或者使用Doctrine Paginator:

$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);
$totalRows = $paginator->count();