Question

I have two entities, Class and Student. One Class can have multiple Students (oneToMany):

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

For fetching all Classes, I'm writing my own query like this:

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

Now I'm trying to fetch a list of Classes, ordered (DESC) by the count of related Students. So that the result would look like:

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

How would I go there? I tried something somewhat like this:

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

(Note: I implement DoctrineExtensions' Date function)

But I'm getting an error:

[Semantical Error] line 0, col 26 near 'students)': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

Was it helpful?

Solution

Try to use this in your Class repository:

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top