好的我有2个表,相关结构如下:
**youtubevideo**
id - int
allViews - relational
**views**
id - int
youtubevideo_id - int
viewCount - int
firstFetch - date
与youtubevideo有很多观点相关。这是由Symfony实体中的OneToMany提供的。
现在,我有2个日期,让我们从日期和日期调用它们。我需要选择所有youtubevideos并按照属于它们的viewCount总和对它们进行排序。
我只想在fromDate和toDate之间使用具有firstFetch日期的视图。
所以我想它会像
SELECT y FROM YTScraperBundle:YouTubeVideo y
JOIN y.allViews v GROUP BY y.id
ORDER BY SUM(v.viewCount) LIMIT 0, 30; <-- or does this need to be an inline select to the specific element?
我并没有真正看到如何将WHERE v.firstFetch放在fromDate和toDate之间。
更新
$query = $this->em->createQuery(
"SELECT y, IF(v IS NULL, 0, SUM(v.viewCount)) AS HIDDEN sumviewcount
FROM YTScraperBundle:YouTubeVideo y
LEFT JOIN y.allViews v WITH v.firstFetch BETWEEN :fromDate AND :toDate
GROUP BY y ORDER BY sumviewcount DESC
"
);
$query->setMaxResults(self::PR_PAGE);
$query->setFirstResult($firstResult);
$query->setParameter('fromDate', $fromDate);
$query->setParameter('toDate', $toDate);
获取错误:
Expected known function, got 'IF'
答案 0 :(得分:3)
您必须使用WITH
,BETWEEN
,并将两个DateTime
对象绑定到参数化查询中:
$result = $this->getDoctrine()->getManager()->createQuery('
SELECT y,
CASE WHEN (v IS NULL) THEN 0 ELSE SUM(v.viewCount) END AS HIDDEN sumviewcount
FROM YTScraperBundle:YouTubeVideo y
LEFT JOIN y.allViews v WITH v.firstFetch BETWEEN :fromDate AND :toDate
GROUP BY y ORDER BY sumviewcount DESC
')->setParameter('fromDate', new \DateTime('12-34-5678 00:00:00')) // Replace this with an ISO date
->setParameter('toDate', new \DateTime('12-34-5678 00:00:00')) // Replace here too
->getResult();
我combined @Matteo's answer concerning the SUM
into mine for posterity。对HIDDEN
想法感激不尽。
答案 1 :(得分:3)
对于排序,您可以使用HIDDEN
Doctrine2功能(自Doctrine 2.2 +以来可用)。
SELECT y,
SUM(v.viewCount) AS HIDDEN sumviewcount
FROM YTScraperBundle:YouTubeVideo y
JOIN y.allViews v
GROUP BY y
ORDER BY sumviewcount
LIMIT 0, 30;
查看this文章。
希望这个帮助