php - Symfony2 Doctrine 将所有计数视为整数

标签 php symfony doctrine-orm query-builder

我想获取数据库中所有记录的计数。我还没有找到一种推荐的方法来做到这一点。所以我在我的实体存储库中内置了这个函数:

public function countAll()
{
    return $this->createQueryBuilder('post')
        ->select('COUNT(post)')
        ->getQuery()->getSingleScalarResult()
        ;
}

没关系,因为它返回了所有项目的计数。我使用 FOSRestBundle,因此我在 Controller 中的操作如下所示:

public function getPostsCountAction() {
    return $this->em->getRepository('KamilTestBundle:Post')->countAll();
}

地址 posts/count.json 的结果如下所示:

"16"

但是...我想将此值视为整数。我不知道为什么 QueryBuilder 将其作为字符串返回。即使我使用 ->getQuery()->getResult() 并转储此输出,它也是字符串,而不是整数。

如何将此值视为整数?有可能吗?

最佳答案

intval()将返回字符串的数字表示形式。

虽然使用它可能会很困难,但你应该 100% 没问题,因为你知道你只会得到数字。

public function countAll()
{
    return intval($this->createQueryBuilder('post')
        ->select('COUNT(post)')
        ->getQuery()->getSingleScalarResult());
}

关于php - Symfony2 Doctrine 将所有计数视为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627803/

相关文章:

php - 使用基础部分的 php

mysql - 学说 2 : how to use datatype long?

symfony - 从应用程序目录安装 Assets

postgresql - 使用 IS DISTINCT FROM 的 Symfony 原则

mysql - 我的查询很慢

php - Symfony Doctrine Migrations,如何使用多个实体管理器

php - 多个事件日期更新到数据库

php - 需要帮助将我漂亮的 soup (Python) 代码转换为 PHP

php - 两个日期时间之间的记录数

php - 将 MySQL 查询转换为 Symfony Doctrine