Symfony2 : count from the querybuilder

标签 symfony doctrine

我想知道我的表 TABLE 中的行数以及属性 name="joe"

这里是我到目前为止使用的代码,但我检索了对象(这只是不必要的,所以没有优化)

$repository = $this->getDoctrine()->getManager()->getRepository('MyBundle:TABLE');
$name = "joe";
$liste = $repository->findBy(array('name' => $name));
$nombre = count($liste);

如何使用 count 使用 querybuilder 实现它?需要设置参数$name。到目前为止我所看到的都没有参数 like this one ,所以不知道这是如何工作的......(而且我想避免使用分页器)

谢谢。

最佳答案

您可以通过以下方式实现:

$repository = $this->getDoctrine()->getManager()->getRepository('MyBundle:TABLE');
$name = "joe";
$qb = $repository->createQueryBuilder('t');
$qb->select('count(t.id)');
$qb->where('t.name = :name');
$qb->setParameter('name', $name);
$nombre = $qb->getQuery()->getSingleScalarResult();

但是好的做法是将此逻辑放入存储库类中,因此您可以像这样调用方法:
$nombre = $repository->countByName($name); 

只需在您的 TableRepository 类中创建新方法:
public function countByName($name)
{
    $qb = $this->createQueryBuilder('t');
    $qb->select('count(t.id)');
    $qb->where('t.name = :name');
    $qb->setParameter('name', $name);

    return $qb->getQuery()->getSingleScalarResult();
}

关于Symfony2 : count from the querybuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532349/

相关文章:

php - 如何在 Symfony 2 中使用 ajax 登录?

symfony - 使用 Doctrine 将实体与不同的子类合并

php - 如何访问 Doctrine2 中 PrePersist LifecycleCallback 的旧值

php - Doctrine 2继承映射找不到基表或 View

php - JMS 序列化 @VirtualProperty 不起作用

php - 没有 Doctrine 的 Symfony2

mysql - Doctrine DBAL 查询构建器连接和 where 子句

php - 交响乐 4 : How to pass the $_SERVER array as constructor argument

php - 使用 Doctrine Symfony2 中的查询生成器实现 SQL 联合查询

php - Doctrine 2 findBy* 返回对象