php the right way中文



如何在symfony版本庫中使用group by (1)

我會盡力提供解決方案和解釋,這可能會幫助你。

假設你有這樣的表結構:

而且你想得到dayOfWeek分組的所有記錄與在這一天將進行講座(分別用逗號分隔)的講師名單。

你可能會想出這樣的事情:

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

結果將是:

另外,如果你想獲取提取記錄的ID列表,你可以這樣寫:

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

所以結果是:


而且,如果我正確理解你的問題,這個答案可能會對你有所幫助。

我在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]);
}

day/listAll.html.twig{{ 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}
  }
]

我真正需要的是對結果進行分組,以便將dayOfWeek0所有結果組合在一起? 我需要根據dayOfWeek屬性對結果進行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

謝謝你的時間。





group-by