如何获取相关实体的行数?

时间:2013-12-09 16:40:09

标签: symfony count doctrine one-to-many

我有两个实体ClassStudent。一个Class可以有多个Student s(oneToMany):

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

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

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

现在我正在尝试通过相关Class的计数来获取Student es,ordered(DESC)的列表。结果如下:

Class.id   Class.count(Student)
--------   --------------------
       3                    109
       1                     81
       4                     58
       2                     21

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

SELECT
    c,
    COUNT(c.students) AS students
FROM MyBundle:Class c
WHERE c.whatever = :param
GROUP BY c.id
ORDER BY students DESC

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

但是我收到了一个错误:

  

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

1 个答案:

答案 0 :(得分:3)

尝试在Class存储库中使用它:

public function getAllClassesOrderedByNumberOfStudents()
{
    $qb = $this->createQueryBuilder('class');

    $buffer = $qb
        ->select('class, COUNT(students) AS students_per_class')
        ->innerJoin('class.students', 'students')
        ->groupBy('class.id')
        ->orderBy('students_per_class', 'DESC');

    $q = $buffer->getQuery();

    return $q->getResult();
}