symfony2 / doctrine:如何使用带有count的ResultSetMapping

时间:2015-05-14 14:34:57

标签: symfony doctrine-orm doctrine sqlresultsetmapping

我有一个存档表(id,title,author)和一个download_history表(id,id_archive,date)来跟踪每个存档的下载量。现在,我想构建一个报告,以便每周查看下载次数最多的档案。在SQL中做起来很简单,但事情更复杂的是学说,这是我到目前为止所做的:

public function getTopDownloadsLastXDays($limit=100, $days=7)
{
    $rsm = new ResultSetMapping();
    $rsm->addEntityResult('DownloadHistory', 'd');
    $rsm->addMetaResult('d', 'archive', 'archive');
    $rsm->addScalarResult('tot', 'tot');
    $rsm->addJoinedEntityResult('Archive', 'a', 'd', 'archive');
    $rsm->addFieldResult('a', 'author', 'author');
    $rsm->addFieldResult('a', 'title', 'title');

    $sql = "SELECT
              DISTINCT(dh.archive_id),
              COUNT(*) as tot,
              a.author,
              a.title
            FROM
              download_history dh
            INNER JOIN
              archive a
            ON
              dh.archive_id = a.id
            WHERE
              dh.date >= DATE(NOW()) - INTERVAL :days DAY
            GROUP BY
              dh.archive_id
            LIMIT :limit";

    $em = $this->getEntityManager();
    $query = $em->createNativeQuery($sql, $rsm);
    $query->setParameters(array(
        ':days'     =>  $days,
        ':limit'    =>  $limit,
    ));

    $results = $query->getResult();
    return $results;
}

实体存在且工作正常。我按照第三个例子: http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html#examples。这是我的结果:

array(1) { 
    [-1]=> array(1) { 
        ["tot"]=> string(1) "1" 
    } 
}

任何想法?感谢

1 个答案:

答案 0 :(得分:0)

您将表别名为" dh",但您将别名指定为" d"在构建ResultSetMapping时。