如何按关联实体的数量对我的学说结果进行排序,并按时间限制

时间:2013-12-09 17:03:53

标签: symfony doctrine-orm count one-to-many

我有两个实体ClassStudent。一个Class可以有多个Student s,因此它是oneToMany关系。 (不要打扰,它应该是一个很多的关系,我只是举个例子。)

# YAML notation for Entity 'Class'
...
oneToMany:
    students:
        targetEntity: MyBundle\Entity\Student
        mappedBy: class

# YAML notation for Entity 'Student'
...
date: datetime # this is the date where Student joined a Class

为了获取所有Class es,我正在编写我自己的查询:

SELECT c
FROM MyBundle:Class c
WHERE c.whatever = :parameter
ORDER BY c.id DESC

现在我正在尝试获取“上升”Class es的列表。这意味着,在过去五天内由Class加入的所有Student es - 按加入的Student的数量排序(DESC)。

结果如下:

Class.id   Class.count(Student)   Latest Join
--------   --------------------   -----------
       3                     19    2013-12-07
       1                     12    2013-12-08
       4                      8    2013-12-07
       2                      5    2013-12-09

我怎么去那里?我尝试过这样的事情:

SELECT
    c,
    COUNT(c.students) AS students,
    MAX(s.date)
FROM MyBundle:Class c
WHERE c.whatever = :param
AND DATE(s.date) > :fivedayspan
ORDER BY students DESC

(注意:我实现了DoctrineExtensions' Date功能)

我正在设置参数:

$q->setParameter('fivedayspan', date('Y-m-d', strtotime('-5 days')));

但是我收到了一个错误:

  

[语义错误]第0行,第36行靠近'学生)':错误:无效的PathExpression。期望StateFieldPathExpression或SingleValuedAssociationField。

1 个答案:

答案 0 :(得分:-1)

这会有用吗?

SELECT
    c,
    COUNT(c.students) AS c.N,
    MAX(c.date)
FROM MyBundle:Class c
WHERE c.whatever = :param
AND DATE(c.date) > :fivedayspan
ORDER BY c.N DESC