如何在symfony存储库中使用group by

时间:2017-07-17 04:24:18

标签: php symfony group-by

我在DayRepository.php中有这段代码:

public function findAllFromThisUser($user)
    {
        $query = $this->getEntityManager()
            ->createQuery(
                'SELECT d FROM AppBundle:Day d
                WHERE d.user = :user
                ORDER BY d.dayOfWeek ASC'
            )->setParameter('user', $user);
        try{
            return $query->getResult();
        } catch (\Doctrine\ORM\NoResultException $e){
            return null;
        }

    }

在控制器DayController.php中,我有以下代码:

/**
 * @Route("/days/list", name="days_list_all")
 */
public function listAllAction()
{
    $user = $this->container->get('security.token_storage')->getToken()->getUser();

    $days = $this->getDoctrine()
        ->getRepository('AppBundle:Day')
        ->findAllFromThisUser($user);

    //$user = $job->getUser();

    return $this->render('day/listAll.html.twig', ['days' => $days]);
}

{{ dump(days) }}day/listAll.html.twig的输出为:

array:3 [▼
  0 => Day {#699 ▼
    -id: 11
    -dayOfWeek: "0"
    -lessonTime: DateTime {#716 ▶}
    -user: User {#486 ▶}
    -job: Job {#640 ▶}
    -client: Client {#659 ▶}
  }
  1 => Day {#657 ▼
    -id: 13
    -dayOfWeek: "0"
    -lessonTime: DateTime {#658 ▶}
    -user: User {#486 ▶}
    -job: Job {#640 ▶ …2}
    -client: Client {#659 ▶ …2}
  }
  2 => Day {#655 ▼
    -id: 12
    -dayOfWeek: "4"
    -lessonTime: DateTime {#656 ▶}
    -user: User {#486 ▶}
    -job: Job {#640 ▶ …2}
    -client: Client {#659 ▶ …2}
  }
]

我真正需要的是对结果进行分组,以便将dayOfWeek作为0的所有结果组合在一起?我需要根据dayOfWeek属性对结果进行分组。我曾尝试在查询中使用GROUP BY d.dayOfWeek,但我收到此错误:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'taskMaestro.d0_.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

我会尝试提供解决方案和解释,这可能会对您有所帮助。

假设你有这样的表结构: enter image description here

并且您希望获得按dayOfWeek分组的所有记录以及在当天进行讲座的演员列表(分别用逗号分隔)。

你可能会想出这样的事情:

SELECT `dayOfWeek`, GROUP_CONCAT(`lector`) AS `dayLectors` FROM `day` GROUP BY `dayOfWeek`

结果将是:
enter image description here

另外,如果您想获取已获取记录的ID列表,可以这样写:

SELECT `dayOfWeek`, GROUP_CONCAT(`lector`) AS `dayLectors`, GROUP_CONCAT(`id`) AS `dayIds` FROM `day` GROUP BY `dayOfWeek`

结果将是:
enter image description here


而且,如果我理解你的问题是正确的,这个答案可能对你有帮助。