- Published on
doctrine教程8---选择SUM(或COUNT)
原创文章,转载时需取得本人同意并注明来源
- Authors
-
-
- Name
- langziyang
-
在我们的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,效果是一样的
调用这个方法后我们就得到了一个总数