【问题标题】:How to fetch row count of related entities?如何获取相关实体的行数?
【发布时间】:2013-12-10 04:03:20
【问题描述】:

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

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

为了获取所有Classes,我正在编写自己的查询,如下所示:

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

现在我正在尝试获取Classes 的列表,按相关Students 的计数排序(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函数)

但我收到一个错误:

[Semantical Error] line 0, col 26 near 'students)': Error: Invalid PathExpression。需要 StateFieldPathExpression 或 SingleValuedAssociationField。

【问题讨论】:

  • 尝试将GROUP BY c.id 添加到您的查询中。
  • 我做了,还是一样的错误信息。

标签: symfony count doctrine one-to-many


【解决方案1】:

尝试在您的 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();
}

【讨论】:

  • 很抱歉这么晚才接受,不知何故从我的视线中消失了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
相关资源
最近更新 更多