我有一个存档表(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"
}
}
任何想法?谢谢