doctrine教程8---选择SUM(或COUNT)

Mario Sanchez

18 people read
Thumbnail

在我们的FortuneCookie有一个$numberPrinted属性,如果我们想要统计所有数据的总数

我们可以通过循环 $category->getFortuneCookies() ...调用 ->getNumberPrinted()然后相加,如果我们只有少量的Cookies,那没问题,反之就可能会耗尽内存

让我们想想:我们查询的数据最终将来自 FortuneCookie 实体...因此打开 FortuneCookieRepository 以便我们可以在其中添加一个新方法。怎么样: public function countNumberPrintedForCategory(Category $category): int

public function countNumberPrintedForCategory(Category $category): int
    {
        $result = $this->createQueryBuilder('fortuneCookie')
            ->select('SUM(fortuneCookie.numberPrinted) AS fortunesPrinted')
            ->andWhere('fortuneCookie.category = :category')
            ->setParameter('category', $category)
            ->getQuery()
            ->getSingleScalarResult();
        return (int)$result;
    }

我们之前用的->addSelect(),但是现在我们使用->select方法,addSelect可以理解为,选择需要的内容并且选择我们添加的其它内容。同时还能看到在添加where时我们使用了整个Category实体,其实这里你也可以传id,效果是一样的

调用这个方法后我们就得到了一个总数

About Me

我是一位精通 Symfony 框架和 API Platform 的开发者,擅长构建高效、可扩展的 Web 应用程序和 API。 此外,我还具备 PrestaShop 模块开发经验,能够为您的电商平台定制功能,满足特定业务需求。