【问题标题】:Doctrine 2 - GROUP BY two columns, gets incorrect valuesDoctrine 2 - GROUP BY 两列,得到不正确的值
【发布时间】:2021-12-08 23:57:01
【问题描述】:

在我的数据库中,我有与tasks 相关的表与user 表。 我想获取特定状态的任务列表,按用户和状态分组。 这是我的查询:

$this->createQueryBuilder('t')
      ->select('t.assignee, COUNT(t.id) as count, t.state')
      ->join('t.assignee', 'user')
      ->andWhere('t.state IN (:states)')
      ->setParameters([
         'states' => array($states)
      ])
      ->addGroupBy('t.assignee')
      ->addGroupBy('t.state')
      ->getQuery()
      ->getResult()

不幸的是,该查询没有返回正确的记录。结果是每个用户只有一条记录,尽管它应该返回一个用户的一些记录,按任务类型排序。 你能帮我更正我的问题吗?

【问题讨论】:

    标签: symfony doctrine-orm


    【解决方案1】:

    你必须先设置groupBy方法,然后再使用addGroupBy方法。

    您的代码将如下所示:

    $this->createQueryBuilder('t')
          ->select('t.assignee, COUNT(t.id) as count, t.state')
          ->join('t.assignee', 'user')
          ->andWhere('t.state IN (:states)')
          ->setParameters([
             'states' => array($states)
          ])
          ->groupBy('t.assignee')
          ->addGroupBy('t.state')
          ->getQuery()
          ->getResult()
    

    【讨论】:

      【解决方案2】:

      也将andWhere 更改为where

      $em = $this->getDoctrine()->getManager();
      $query = $em->getRepository('App:Entity')->createQueryBuilder('t');
      $query
            ->select('t.assignee, COUNT(t.id) as count, t.state')
            ->join('t.assignee', 'user')
            ->where($query->expr()->in('t.state', array($states)))
            ->groupBy('t.assignee')
            ->addGroupBy('t.state')
            ->getQuery()
            ->getResult();
      

      【讨论】:

        猜你喜欢
        • 2013-03-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-28
        • 2011-01-12
        • 1970-01-01
        • 2023-01-13
        • 1970-01-01
        • 2011-10-07
        相关资源
        最近更新 更多